springMVC实现文件上传

通过maven引入相关jar包

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
配置springmvc上传配置
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>

springMvc上传代码
@RequestMapping("upload"  )  
public String upload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
//创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
//记录上传过程起始时的时间,用来计算上传时间
int pre = (int) System.currentTimeMillis();
//取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if(file != null){
//取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
//如果名称不为“”,说明该文件存在,否则说明该文件不存在
if(myFileName.trim() !=""){
System.out.println(myFileName);
//重命名上传后的文件名
String fileName = "SpringMVCUpload/" + file.getOriginalFilename();
//定义上传路径
String path = "D:/" + fileName;
File localFile = new File(path);
file.transferTo(localFile);
}
}
//记录上传该文件后的时间
int finaltime = (int) System.currentTimeMillis();
System.out.println(finaltime - pre);
}

}
return "forward:home/success.jsp";
}



posted @ 2016-10-23 18:55  煮海焚天  阅读(541)  评论(0编辑  收藏  举报