SpringMVC文件上传与下载
一、上传
1.在springMVC配置文件中声明multipart解析器。使用StandardServletMultipartResolver不需要导入额外的jar包
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
</bean>
2.web.xml配置Multipart,我们必须指定文件上传过程中所写入的临时文件路径,否则StandardServletMultipartResolver无法正常工作
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<multipart-config>
<location>E://topic/tmp/uploads</location>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3.文件上传Controller方法
@ResponseBody
@PostMapping("/upload/{topicId}")
public Map upload(@PathVariable int topicId, @RequestPart("file") MultipartFile file) {
Map map=new HashMap();
map.put("code","0");
try{
String original = file.getOriginalFilename(); //获取文件名
String suffix = original.substring(original.lastIndexOf('.')); //获取文件后缀
String filename = "E://topic/uploads/调查报告"+topicId+suffix; //重名名
file.transferTo(new File(filename)); //写入文件系统
Map m = new HashMap();
m.put("src",filename);
map.put("data",m);
map.put("msg","上传成功!");
}catch (Exception e){
map.put("data",null);
map.put("msg","上传失败!");
}
return map;
}
二、下载
1.文件下载Controller方法
@GetMapping("/download/{topicId}")
public ResponseEntity<byte[]> download(@PathVariable int topicId) throws IOException {
String filename=surveyService.getPath(topicId); //surveyService.getPath获取文件路径
File file = new File(filename);
InputStream is = new FileInputStream(file);
byte[] body = new byte[is.available()];
is.read(body);
is.close();
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Disposition", "attachment;filename=" + file.getName());
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
return entity;
}
2.前端请求下载文件时,不能使用ajax,使用ajax请求下载时浏览器不会弹出下载提示框,可使用window.location.href进行请求
window.location.href = "/topic/download/" + id;