本文主要介绍SpringMVC上传文件的两种方式
第二种较第一种而言,采用了解析器,大大提高了上传的效率。
第一种:
步骤:
1、引入jar包
2、配置spring-servlet.xml文件
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="200000"/>
<property name="defaultEncoding" value="utf-8" />
<property name="maxInMemorySize" value="40960" />
</bean>
<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
</props>
</property>
</bean>
3、写jsp
文件上传方式,必须要采用POST!
设置表单的编码方式,必须为enctype="multipart/form-data">
<h>上传</h>
<form name="userForm" action="/springMVC7/file/upload" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="filename">
<input type="submit" value="提交">
</form>
4、写Controller
利用springMVC封装好的上传文件的方法,用注解的方式拿到JSP中的文件。(@RequestParam("filename")
@Controller
@RequestMapping("/file")
public class index {
@RequestMapping(value = "/upload1")
public String addUser(@RequestParam("filename") CommonsMultipartFile file,
HttpServletRequest request) throws IOException {
if (!file.isEmpty()) {
try {
// 拿到输出流,同时重命名上传的文件
FileOutputStream os = new FileOutputStream("D:/" + new Date().getTime()
+ file.getOriginalFilename());
// 拿到上传文件的输入流
InputStream in = file.getInputStream();
// 以写字节的方式写文件
int b = 0;
while ((b = in.read()) != -1) {
os.write(b);
}
os.flush();
os.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return "success";
}
第二种:优化上传文件
思路:使用解析器,大大提高了上传速度
与方法一的区别仅在于Controller
@RequestMapping("/upload2")
public String upload2(HttpServletRequest request, HttpServletResponse response)
throws IllegalStateException, IOException {
// 创建一个通用的多部分解析器 ,用于解析SpringMVC的上下文
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request
.getSession().getServletContext());
// 解析request,判断是否为MultipartFile类型数据,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {
// 取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
// 如果名称不为“”,说明该文件存在,否则说明该文件不存在
if (myFileName.trim() != "") {
// 重命名上传后的文件名
String fileName = new Date().getTime()
+ file.getOriginalFilename();
/*
* //定义上传路径 String path = "H:/" + fileName; File
* localFile = new File(path); //
* 把文件拷贝到本地:transferTo(gest)将上传文件写到服务器指定文件上
* file.transferTo(localFile);
*/
// 如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
String realPath = request.getSession().getServletContext()
.getRealPath("/WEB-INF/upload");
// 不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(
realPath, fileName));
}
}
}
}
return "/success";
<span style="font-family:Microsoft YaHei;">}</span>
总结:
本文主要介绍SpringMVC上传文件的两种方式。利用SpringMVC对上传文件封装的方法,做上传操作。
第二种较第一种而言,采用了解析器,大大提高了上传的效率。
当然,并不建议使用SpringMVC的上传方式,因为此时是将文件先上传到服务器后,才做验证!
推荐使用前台JQuery等上传文件的方式,只需要在浏览器做验证即可,不需要提交服务器,更加提高传输效率。