【开发心得】Sring boot 获取资源文件
  OIW0KlaMcRRl 2023年11月28日 31 0


 

在读取springBoot构建的项目时,如果使用传统的FileInputStream读取文件流或者ResourceUtils工具类的方式

File file= ResourceUtils.getFile("classpath:test.xlsx");   

可能会出现File is not found的问题。

在springboot中可以使用ClassPathResource获取文件流的方式方便下载文件

try {
    ClassPathResource classPathResource = new ClassPathResource("test.xlsx");
    File file = classPathResource.getFile();
    InputStream inputStream = classPathResource.getInputStream();
      //输出文件
    InputStream fis = new BufferedInputStream(inputStream);
    byte[] buffer = new byte[fis.available()];
    fis.read(buffer);
    fis.close();
    response.reset();

    //获取文件的名字再浏览器下载页面
    String name = file.getName();
    response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "iso-8859-1"));
    response.addHeader("Content-Length", "" + file.length());
    OutputStream out = new BufferedOutputStream(response.getOutputStream());
    response.setContentType("application/octet-stream");
    out.write(buffer);
    out.flush();
    out.close();
} catch (Exception e) {
    e.printStackTrace();
}
最后就是浏览器访问接口下载文件了
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月28日 0

暂无评论

推荐阅读
OIW0KlaMcRRl