springboot各种下载文件的方式汇总

下载功能其实就是用户输入指定文件路径信息,然后把文件返回给用户,下面这篇文章主要给大家介绍了关于springboot各种下载文件的方式,需要的朋友可以参考下

+

目录

一、使用response输出流下载

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@GetMapping("/t2")

public ResponseEntity<InputStreamResource> 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<ByteArrayResource> 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

1

2

3

4

5

6

7

8

9

10

@PostMapping("/t4")

    public ResponseEntity<ByteArrayResource> 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):

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

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script>

      function download() {

        var ajax = new XMLHttpRequest();

        ajax.withCredentials = true;

        ajax.responseType = "blob";

        const fileName = "ttt.txt";

        ajax.open('post','http://localhost:7901/demo/down/file/t4?fileName=' +  fileName);

        ajax.setRequestHeader("Content-Type","application/json;charset=utf-8");

        // ajax.setRequestHeader("Accept","application/json;charset=utf-8");

        ajax.send(JSON.stringify({firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"}));

        ajax.onreadystatechange = function () {

          if (ajax.readyState==4 &&ajax.status==200) {

            console.log(ajax.response);

              const href = URL.createObjectURL(ajax.response);

              const a = document.createElement('a');

              a.setAttribute('href', href);

              a.setAttribute('download', fileName);

              a.click();

              URL.revokeObjectURL(href);

          }

        }

      }

    </script>

</head>

<body>

  <input type="button" value="下载" onclick="download();"/>

</body>

</html>

总结

到此这篇关于springboot各种下载文件的文章就介绍到这了,更多相关springboot下载文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值