SpringMVC文件上传
单文件上传
- 导入依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
- 配置文件上传解析器
<!-- 配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件总大小-->
<property name="maxUploadSize" value="102400" />
<!-- 上传单个文件大小-->
<property name="maxUploadSizePerFile" value="10240" />
<!-- 上传文件的编码类型-->
<property name="defaultEncoding" value="utf-8" />
</bean>
- 配置controller
@RequestMapping("/simple.do")
public ModelAndView uploadSimple(String name, MultipartFile uploadFile) throws IOException {
//获得文件名称
ModelAndView modelAndView = new ModelAndView();
String filename = uploadFile.getOriginalFilename();
System.out.println(filename);
InputStream is = uploadFile.getInputStream();
byte[] bytes = new byte[1024];
int len;
while((len = is.read(bytes)) != -1){
System.out.println(new String(bytes,0,len));
}
//保存文件
uploadFile.transferTo(new File("D:\\upload\\"+filename));
modelAndView.addObject("filename",filename);
modelAndView.setViewName("purpose");
return modelAndView;
}
- 界面设计
<form action="upload/simple.do" method="post" enctype="multipart/form-data">
文件:<input type="file" name="uploadFile">
<input type="submit" value="上传">
</form>
tips: 文件上传 method 必须为 post.表单input中的name属性必须与Controller方法中的参数名一致。
多文件上传
- 导入依赖。
- 配置文件上传解析器。
- 配置Controller。
@RequestMapping("/multi.do")
public ModelAndView uploadMulti(String name, MultipartFile[] uploadFiles) throws IOException {
ModelAndView modelAndView = new ModelAndView();
ArrayList<String> list = new ArrayList<>();
for (MultipartFile uploadFile : uploadFiles) {
String filename = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("D:\\upload\\"+filename));
list.add(filename);
}
modelAndView.addObject("filenames",list);
modelAndView.setViewName("goal");
return modelAndView;
}
- 界面设计。
<form action="upload/multi.do" method="post" enctype="multipart/form-data">
文件:<input type="file" name="uploadFiles">
文件:<input type="file" name="uploadFiles">
文件:<input type="file" name="uploadFiles">
<input type="submit" value="上传">
</form>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<c:forEach var="filename" items="${filenames}" varStatus="s">
<h2>文件${filename}上传成功!</h2>
</c:forEach>
</body>
</html>