springboot如何下载resource目录下的文件

Java技术 潘老师 1年前 (2023-03-20) 1808 ℃ (0) 扫码查看

有时候我们会将一些静态模板文件,比如一些导入excel的模版放在resource目录下,那么我们springboot该如何实现resource目录下的文件下载功能呢?

这里我们现将一个名为xxx模板.xls的文件放在resource目录的下的template文件夹下,接下来我们写如下代码即可实现下下载功能:

@GetMapping("/download/template")
    public void downloadTemplate(HttpServletRequest request, HttpServletResponse response){
        String fileName = request.getParameter("fileName");
        InputStream is = null;
        OutputStream os = null;
        try {
            is = this.getClass().getClassLoader().getResourceAsStream("template"+ File.separator+fileName);
            os = response.getOutputStream();
            byte[] bytes = StreamUtils.copyToByteArray(is);
            response.reset();
            //下面这两行是为了解决跨域,如果没有跨域这两行可以删除
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.setContentType("application/octet-stream;charset=utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            response.addHeader("Content-Length", "" + bytes.length);
            os.write(bytes);
            os.flush();
        }catch (Exception e) {
            log.error("下载出错", e);
        }finally {
            try {
                if(os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            }catch (Exception e) {
                log.error("关闭流出错", e);
            }
        }
    }

接下来我们只需要发送类似:localhost:8080/api/download/template?fileName=xxx模板.xls的get请求就可以触发该下载方法,从而现在springboot如何下载resource目录下的文件的下载了。


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/java/5916.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】