当前位置:   article > 正文

SpringBoot获取resources下的文件_springboot resources outputstream

springboot resources outputstream

例如下载/resources/excel/template.xlsx

    @GetMapping("/download")
    public void downloadFile(HttpServletRequest request,
                             HttpServletResponse response) {
        String fullFileName = "excel/template.xlsx";
        ExcelUtils.exportLocalExcel(request, response, fullFileName);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

ExcelUtils.java

public class ExcelUtils {

    /**
     * 导出本地Excel
     *
     * @param httpRequest  请求信息
     * @param httpResponse 响应信息
     * @param pathFileName 带路径的文件名字
     */
    public static void exportLocalExcel(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String pathFileName) throws Exception {
        String[] split = pathFileName.split("/");
        ClassPathResource classPathResource = new ClassPathResource(pathFileName);
        InputStream fis = classPathResource.getInputStream();
        httpResponse.setContentType("application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String rawFileName = split[split.length - 1];
        String fileName = FileNameUtil.getPrefix(rawFileName);
        String suffix = FileNameUtil.getSuffix(rawFileName);
        httpResponse.setHeader("Content-Disposition", "attachment;filename=" + getFileName(fileName, httpRequest) + "." + suffix);
        ServletOutputStream outputStream = httpResponse.getOutputStream();
        if (fis.available() != 0) {
            httpResponse.setStatus(200);
        }
        IOUtils.copy(fis, outputStream);
        fis.close();
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 处理文件名字编码
     *
     * @param fileName 文件名字
     * @param request  请求信息
     * @return 编码后文件名
     * @throws Exception 异常信息
     */
    private static String getFileName(String fileName, HttpServletRequest request) throws Exception {
        String ua = request.getHeader("User-Agent").toLowerCase();
        if (ua.contains("macintosh") && !ua.contains("chrome")) {
            //浏览器: safari
            return new String(fileName.getBytes(), "ISO8859-1");
        }
        //默认utf-8
        return URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/815919?site
推荐阅读
相关标签
  

闽ICP备14008679号