springMVC上传图片案例2

2018年03月07日 10:41 | 2866次浏览 作者原创 版权保护

一、前言

上一章讲述了在jetty下springMVC上传图片,但是好多开发者应该用的是tomcat,所以站长亲自配置了下一个通用的springMVC上传图片的demo,并测试成功。

二、controller代码

/***
V型知识库 原创 www.vxzsk.com
*****/
@RequestMapping(value="/uploadTop",method=RequestMethod.POST)
	public void uploadPage(MultipartHttpServletRequest multipartRequest,
			   HttpServletResponse response,HttpServletRequest request) throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		
		  response.setContentType("text/html;charset=UTF-8");  
		  //System.out.println("ddddd");
		  String realPath = multipartRequest.getSession()
			       .getServletContext()
			       .getRealPath("upload/top");
		  System.out.println(realPath);
		  String jpgName=UUID.randomUUID().toString()+sdf.format(new Date());
			 MultipartFile file= multipartRequest.getFile("houseMaps");
			 //System.out.println(file.getOriginalFilename()+"=================");
			// String fileName = file.getOriginalFilename();
			 
			 File file2 = new File(realPath+"/"+jpgName+".jpg");
				FileCopyUtils.copy(file.getBytes(),file2);
				System.out.println(realPath+"/"+jpgName+".jpg");
				 String result="{result:'"+jpgName+"'}";
				 response.getWriter().print(result);  
		
	}

注意:代码中文件接收名字为houseMaps,FileCopyUtils工具类为org.springframework.util.FileCopyUtils;

三、配置文件ApplicationContext.xml加入上传代码

<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> 
    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --> 
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
        <!-- 指定所上传文件的总大小不能超过5000KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> 
        <property name="maxUploadSize" value="52428800"/>
        <property name="maxInMemorySize">  
           <value>2048</value>  
        </property> 
    </bean>


四、jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>单图片上传</title>
</head>
<body>
<fieldset>
<legend>图片上传</legend>
<h2>只能上传单张10M以下的 PNG、JPG、GIF 格式的图片</h2>
<form action="b/uploadTop.do" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="houseMaps">
    <input type="submit" value="上传"> 
</form>
</fieldset>
</body>
</html>

注意:form表达的请求action路径,以及选择文件的input名字必须为houseMaps(与controller方法中接收一致)



小说《我是全球混乱的源头》
此文章本站原创,地址 https://www.vxzsk.com/610.html   转载请注明出处!谢谢!

感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程