当前位置:   article > 正文

SpringBoot 实现文件下载功能_springboot 下载文件

springboot 下载文件

笔主本来直接通过File去实现下载功能,打成jar后发现,File寻找文件是找不到的,因为文件是打到jar包中的,jar本身是一个文件,文件中是无法通过file进入目录获取的,只能通过类加载器加载资源得到流,对流进行处理。 所以采用了如下的办法改造代码,实现文件下载功能。
如下是错误代码案例:(本地的开发环境可以下载,但是打出jar包却不能下载)

        @RequestMapping("/download")
    public void download(String type, HttpServletResponse response) {
        try {
            String path="";
            if ("example".equals(type)) {
                 path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/assets/download/xxx1.excel";
            }else if("readMe".equals(type)){
                path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/assets/download/xxx2.excel";
            }else{
                return;
            }
    // path是指想要下载的文件的路径
            File file = new File(path);
    // 获取文件名
            String filename = file.getName();
    // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
    // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

    // 清空response
            response.reset();
    // 设置response的Header
            response.setCharacterEncoding("UTF-8");
    //Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
    //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
    // filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

  • 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

正确的代码如下:

@RequestMapping("/download")
    public void download(String type, HttpServletResponse response) {
        try {
            InputStream is = null;
            String filename="";
            if ("example".equals(type)) {
                 is = getClass().getResourceAsStream("/static/assets/download/xxx1.excel");
                filename="xxx1.excel";
            }else if("readMe".equals(type)){
                 is = getClass().getResourceAsStream("/static/assets/download/xxx2.excel");
                filename="xxx2.excel";
            }else{
                return;
            }
            if(Objects.isNull(is)) {
                return;
            }
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            byte[] buffer = new byte[1024];
            int i;
            ServletOutputStream os = response.getOutputStream();
            while ((i = is.read(buffer, 0, buffer.length)) != -1) {
                os.write(buffer, 0, i);
            }
            is.close();
            os.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
  • 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

最终实现文件下载功能。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/873388
推荐阅读
相关标签
  

闽ICP备14008679号