spring文件上传下载方法

springMVC文件上传依赖commons-fileupload组件,做了封装.

  • 添加io,fileupload依赖包

  • 配置文件解析器bean对象到容器

<!--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);
}
posted @ 2021-04-26 11:35  张--  阅读(240)  评论(0)    收藏  举报