springboot文件下载案例

service层下载文件的方法:

1、加入依赖

<!--文件流处理工具包-->
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.2</version>
</dependency>

 

2、在springboot的application.properties文件中配置文件路径

# 文件存储路径
file.path=C:/image/

 

3、编写下载代码

  @Value("${file.path}")  //注入
  private String filePath;

  @Override
public void download(String fileId, HttpServletResponse response) { SysFile sysFile=sysFileMapper.selectByPrimaryKey(fileId); ServletOutputStream fileOutputStream = null; response.setContentType("multipart/form-data"); try { //万能乱码问题解决 String fileName = new String(sysFile.getFileName().getBytes("UTF-8"), "ISO-8859-1"); // 设置文件下载响应头 response.setHeader("Content-disposition", String.format("attachment;filename=%s",fileName)); } catch (Exception ex) { log.error("e:{}",ex); throw new BusinessException(BaseResponseCode.OPERATION_ERROR); } try { File file=FileUtils.getFile(filePath,sysFile.getFileName()); fileOutputStream = response.getOutputStream();    IOUtils.write(FileUtils.readFileToByteArray(file),fileOutputStream); } catch (IOException e) { log.error("e:{}",e); throw new BusinessException(BaseResponseCode.OPERATION_ERROR); }finally { try { if(fileOutputStream != null){ fileOutputStream.close(); } } catch (IOException e) { log.error("e:{}",e); throw new BusinessException(BaseResponseCode.OPERATION_ERROR); } } }

 

posted @ 2020-09-18 12:46  xueheng_blog  阅读(407)  评论(0编辑  收藏  举报