前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【springboot2.x】实现文件下载

【springboot2.x】实现文件下载

原创
作者头像
无敌小菜鸟
发布2023-02-16 10:18:07
7670
发布2023-02-16 10:18:07
举报
文章被收录于专栏:搬砖笔记

简写了几种下载日志的方法。

一、方法一

代码语言:javascript
复制
    @ApiOperation("日志下载")
    @GetMapping("/logDownload")
    public void download(HttpServletResponse response) {
        try {
            String mulu = "d:/logs";
            ZipUtil.zip(mulu);
            String path = "d:/logs.zip";
            // 压缩日志
            // path是指想要下载的文件的路径
            File file = new File(path);
            log.info(file.getPath());
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            //String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            //log.info("文件后缀名:" + ext);
            // 将文件写入输入流
            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();
        }
    }

二、方法二

代码语言:javascript
复制
    @RequestMapping("/download")
    public ResponseEntity downloadFile() {
        try {
            String mulu = "d:/logs";
            ZipUtil.zip(mulu);
            String path = "d:/logs.zip";
            File file = new File(path);
            InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentLength(file.length());
            headers.setContentType(MediaType.parseMediaType("application/octet-stream"));
            headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
            headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(resource);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

三、方法三

使用hutool工具类实现。

代码语言:javascript
复制
    @GetMapping("/download2")
    public void downloadFile(HttpServletResponse response) {
        try {
            String mulu = "d:/logs";
            ZipUtil.zip(mulu);
            String path = "d:/logs.zip";
            File file = new File(path);
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
            response.addHeader("Content-Length", String.valueOf(file.length()));
            response.addHeader("Content-Range", String.format("bytes 0-%s/%s", file.length() - 1, file.length()));
            //Hutool.copy(new FileInputStream(file), response.getOutputStream(), true);
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();
            IoUtil.copy(fileInputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、方法一
  • 二、方法二
  • 三、方法三
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档