zoukankan      html  css  js  c++  java
  • 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); } } }
  • 相关阅读:
    浅谈自动化测试
    Linux cron定时介绍
    Python上下文管理器
    Robot Framework robot命令
    Web自动化测试之playwright:设置浏览器语言
    Python文件及目录处理方法
    2021google开发者大会
    linux环境变量设置小结
    Eclipse快捷键
    java计时 小计
  • 原文地址:https://www.cnblogs.com/XueTing/p/13690635.html
Copyright © 2011-2022 走看看