spring文件上传下载方法
springMVC文件上传依赖commons-fileupload组件,做了封装.
-
添加io,fileupload依赖包
-
<!--id必须是MultipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="50000000"></property><!--文件最大大小-->
<property name="maxInMemorySize" value="10000000"></property><!--临时文件限制域-->
<property name="uploadTempDir" value="/upload/tmp"></property><!--临时文件存储目录-->
</bean>
下载文件:
@GetMapping("fileDownload")
public ResponseEntity<byte[]> download(HttpServletRequest req, String filePath) throws IOException {
String realPath = req.getServletContext().getRealPath("/");
File file = new File(realPath, filePath);
String name = file.getName();
byte[] bytes = FileUtils.readFileToByteArray(file);
// 下载文件需要添加响应头
HttpHeaders h = new HttpHeaders();
h.add("Content-Disposition","attachment;filename=" +URLEncoder.encode(name,"UTF-8"));
return new ResponseEntity<>(bytes,h,HttpStatus.OK);
}

浙公网安备 33010602011771号