Maven 导包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
SpringMVC 配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="uploadTempDir" value="imgTemp"/>
<property name="maxInMemorySize" value="#{10*1024}"/>
<property name="maxUploadSize" value="#{10*1024}"/>
<property name="maxUploadSizePerFile" value="#{30*1024}"/>
<property name="resolveLazily" value="false"/>
</bean>
Controller
@RestController
@RequestMapping(value = "file")
public class FileController {
@RequestMapping(value = "upload/file", method = RequestMethod.POST)
public String uploadFile(MultipartFile image, HttpServletRequest request) throws IOException {
if (!image.isEmpty()) {
String path = request.getSession().getServletContext().getRealPath("images");
String fileName = image.getOriginalFilename();
File file = new File(path, fileName);
image.transferTo(file);
return "true";
}
return "false";
}
@RequestMapping(value = "upload/files", method = RequestMethod.POST)
public void uploadFiles(MultipartFile[] images, HttpServletRequest request) throws IOException {
for (MultipartFile image : images) {
if (!image.isEmpty()) {
String path = request.getSession().getServletContext().getRealPath("images");
String fileName = image.getOriginalFilename();
File file = new File(path, fileName);
image.transferTo(file);
}
}
}
@RequestMapping(value = "download/file", method = RequestMethod.POST)
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
String path = request.getSession().getServletContext().getRealPath("images");
String fileName = request.getParameter("fileName");
File file = new File(path + "/" + fileName);
if (file.exists()) {
response.setContentType("application/octet-stream");
response.addHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1"));
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
while (inputStream.read(buffer) > 0) {
outputStream.write(buffer);
}
outputStream.close();
inputStream.close();
}
}
}