<form action="testFileUpload" method="post" enctype="multipart/form-data">
File:<input type="file" name="file">
Desc:<input type="text" name="desc">
<input type="submit" value="submit">
</form>
<a href="downloadFile?fileName=上传测试2.txt">下载</a>
@RequestMapping("/testFileUpload")
public String testFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("desc") String desc,
HttpServletRequest request) throws Exception {
System.out.println(file.getOriginalFilename());
// System.out.println(file.getName());
System.out.println(desc);
System.out.println(file.getInputStream());
if (!file.isEmpty()) {
String contextPath = request.getServletContext().getRealPath("/upload");
String originalFilename = file.getOriginalFilename();
File filePath = new File(contextPath);
if (!filePath.exists()) {
filePath.mkdirs();
}
file.transferTo(new File(contextPath + File.separator + originalFilename));
} else {
throw new Exception("请选择上传的文件!");
}
return "success";
}
@RequestMapping("/downloadFile")
public ResponseEntity<byte[]> downloadFile(HttpServletRequest request, @RequestParam("fileName") String fileName) throws IOException {
String realPath = request.getServletContext().getRealPath("/upload");
File downLoadFile = new File(realPath + File.separator + fileName);
byte[] body = FileUtils.readFileToByteArray(downLoadFile);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", fileName);
HttpStatus status = HttpStatus.CREATED;
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, status);
return response;
}
springMVC.xml
<!-- 配置MultipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="1024000"></property>
</bean>
pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>