Spring MVC 方式上传
1. 添加maven依赖
<!-- 文件上传依赖 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
用 maven 添加依赖会自动依赖
commons-io-2.2.jar
手动导包需注意
2. 配置 spring xml文件
<!--文件下载-->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<!--字符集-->
<property name="defaultEncoding" value="UTF-8"/>
<!--最大上传大小 单位字节-->
<property name="maxUploadSize" value="1024000"/>
</bean>
此
bean
中的id
属性必须给出,否则报:Required String parameter 'xxx' is not present
异常
3. 表单页面
<form action="/fileUpload" method="post" enctype="multipart/form-data">
File : <input type="file" name="file"> <br>
DESC : <input type="text" name="desc"> <br>
<input type="submit">
</form>
4. Controller 类
// 文件上传
@RequestMapping("/fileUpload")
public ModelAndView fileUpload(@RequestParam("desc") String desc,
@RequestParam("file") MultipartFile file, HttpSession session) throws IOException {
InputStream in = file.getInputStream();
String rootPath = session.getServletContext().getRealPath("/");
System.out.println(rootPath);
String path = rootPath + "/files/" + file.getOriginalFilename();
File saveFile = new File(path);
if (!saveFile.getParentFile().exists()) {
if (!saveFile.getParentFile().mkdirs()) {
throw new RuntimeException("创建文件夹失败");
}
}
// System.out.println(saveFile.getPath());
// io 操作
FileOutputStream fos = new FileOutputStream(saveFile);
int len = 0;
byte[] bytes = new byte[1024];
while ((len = in.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
in.close();
fos.close();
//视图
String viewName = "success";
ModelAndView modelAndView = new ModelAndView(viewName);
modelAndView.addObject("size", file.getSize());
modelAndView.addObject("contentType", file.getContentType());
modelAndView.addObject("name", file.getName());
modelAndView.addObject("originalFilename", file.getOriginalFilename());
modelAndView.addObject("isEmpty", file.isEmpty());
return modelAndView;
}
5. 多文件上传
只需在入参时用数组接收即可.用循环输出流.
@RequestMapping("/fileUpload2")
public String fileUpload(@RequestParam("desc") String[] desc,
@RequestParam("file") MultipartFile[] file) {
for (int i = 0; i < file.length; i++) {
System.out.println(file[i].getOriginalFilename());
}
return "success";
}