springboot中下载文件的两种方式分享

书欣 SpringBoot 发布时间:2023-07-06 14:26:38 阅读数:7277 1
下文笔者讲述SpringBoot中下载文件的两种方式分享,如下所示

SpringBoot下载文件的实现思路

使用response输出流下载
  或
使用ResponseEntity
例:SpringBoot下载文件的示例

一、使用response输出流下载

@GetMapping("/test1")
    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("/test2")
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("/test3")
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);
}

@PostMapping("/test4")
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);
}

前端代码

<!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 = "test.txt";
        ajax.open('post','http://localhost:8808/demo/down/file/test4?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>
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202307/7013.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者