文件上传依靠commons-fileupload和commons-io两个插件,并使用MultipartFile和MultipartResolver两个类,前者代表上传的文件,后者用于上传文件。
1. pom.xml中添加依赖
<!-- fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- IO operation -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
2. upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div class="upload">
<form action="upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/><br/>
<input type="submit" name="upload"/>
</form>
</div>
</body>
</html>
3. WebMvcConfigurerAdapter中实例化MultipartResolver
该Bean被Servlet用来解析含有MultipartFile部分的Request,并为其传递一个组装好的HttpServletRequest。然后Controller 将这一请求向下转换成为MultipartHttpServletRequest(接口),再通过该接口可以获取MultipartFile。
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver =
new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1000000);
return multipartResolver;
}
4. Controller
package com.controller;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class MultipartController {
/**映射了form中的upload动作,直接使用HttpServletRequest的MultipartFile作为方法参数
* 也可以使用HttpServletRequest作为参数,将其向下转换成MultipartHttpServletRequest,
* 在通过该接口获取MultipartFile
* @param file
* @return
*/
@RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String upload(MultipartFile file) {
try {
FileUtils.writeByteArrayToFile(
new File("/Users/apple/" + file.getName()), file.getBytes());
return "ok";
} catch (Exception ex) {
ex.printStackTrace();
return "wrong";
}
}
}