栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot:各种下载文件的方式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot:各种下载文件的方式

文章目录
  • springboot:各种下载文件的方式
    • 一、使用response输出流下载
    • 二、使用ResponseEntity
    • 三、注意

springboot:各种下载文件的方式 一、使用response输出流下载

注意第一种方式返回值必须为void

@GetMapping("/t1")
    public void down1(HttpServletResponse response) throws Exception {
        response.reset();
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader(
                "Content-disposition",
                "attachment; filename=test.png");
        try(
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\desktop\1.png"));
                // 输出流
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        ){
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = bis.read(buff)) > 0) {
                bos.write(buff, 0, len);
            }
        }
    }
二、使用ResponseEntity
    @GetMapping("/t2")
    public ResponseEntity down2() throws Exception {
        InputStreamResource isr = new InputStreamResource(new FileInputStream("E:\desktop\1.png"));
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-disposition", "attachment; filename=test1.png")
                .body(isr);
    }

    @GetMapping("/t3")
    public ResponseEntity down3() throws Exception {
        byte[] bytes = Files.readAllBytes(new File("E:\desktop\1.png").toPath());
        ByteArrayResource bar = new ByteArrayResource(bytes);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-disposition", "attachment; filename=test2.png")
                .body(bar);
    }
三、注意

后端使用前三种的一种方式,请求方式使用非GET请求,前端使用Blob类型接收

某些情况下,在下载时需要向后端POST一些参数,这时需要前端做一定配合,将接收类型设定为Blob

@PostMapping("/t4")
    public ResponseEntity down4(String fileName, @RequestBody Map data) throws Exception {
        System.out.println(data);
         byte[] bytes = Files.readAllBytes(new File("E:\desktop\1.png").toPath());
        ByteArrayResource bar = new ByteArrayResource(bytes);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-disposition", "attachment; filename=test.png")
                .body(bar);
    }

前端代码(这里使用了原生的ajax):




    
    Title
    


  


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/949078.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号