SpringBoot中都有哪些下载文件的方法汇总?
- 内容介绍
- 文章标签
- 相关推荐
本文共计858个文字,预计阅读时间需要4分钟。
目录
一、使用response输出流下载
二、使用ResponseEntity下载
三、注意事项
四、总结
一、使用response输出流下载
使用response输出流下载文件是一种常见的方法。以下是一个简单的示例:java@GetMapping(/t1)public void down1(HttpServletResponse response) throws IOException { // 模拟文件路径 String filePath=path/to/your/file; // 获取文件名 String fileName=example.txt; // 设置文件下载头 response.setContentType(application/octet-stream); response.setHeader(Content-Disposition, attachment;filename= + fileName); // 读取文件并写入输出流 try (InputStream in=new FileInputStream(filePath); OutputStream out=response.getOutputStream()) { byte[] buffer=new byte[1024]; int length; while ((length=in.read(buffer)) > 0) { out.write(buffer, 0, length); } }}
二、使用ResponseEntity下载使用ResponseEntity下载文件可以提供更灵活的响应头设置。以下是一个示例:
java@GetMapping(/t1)public ResponseEntity down2() { // 模拟文件路径 String filePath=path/to/your/file; // 获取文件名 String fileName=example.txt; // 创建Resource对象 Resource resource=new UrlResource(filePath); // 设置文件下载头 return ResponseEntity.ok() .header(Content-Disposition, attachment;filename= + fileName) .body(resource);}
三、注意事项
1.确保文件路径正确,避免文件不存在的情况。
2.设置正确的文件类型和内容长度。
3.使用try-with-resources语句确保资源被正确关闭。
四、总结
本文介绍了两种在Spring Boot中实现文件下载的方法:使用response输出流和使用ResponseEntity。两种方法各有优缺点,选择合适的方法取决于具体需求。目录
- 一、使用response输出流下载
- 二、使用ResponseEntity
- 三、注意
- 总结
一、使用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<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
@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):
<!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','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下载文件内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!
本文共计858个文字,预计阅读时间需要4分钟。
目录
一、使用response输出流下载
二、使用ResponseEntity下载
三、注意事项
四、总结
一、使用response输出流下载
使用response输出流下载文件是一种常见的方法。以下是一个简单的示例:java@GetMapping(/t1)public void down1(HttpServletResponse response) throws IOException { // 模拟文件路径 String filePath=path/to/your/file; // 获取文件名 String fileName=example.txt; // 设置文件下载头 response.setContentType(application/octet-stream); response.setHeader(Content-Disposition, attachment;filename= + fileName); // 读取文件并写入输出流 try (InputStream in=new FileInputStream(filePath); OutputStream out=response.getOutputStream()) { byte[] buffer=new byte[1024]; int length; while ((length=in.read(buffer)) > 0) { out.write(buffer, 0, length); } }}
二、使用ResponseEntity下载使用ResponseEntity下载文件可以提供更灵活的响应头设置。以下是一个示例:
java@GetMapping(/t1)public ResponseEntity down2() { // 模拟文件路径 String filePath=path/to/your/file; // 获取文件名 String fileName=example.txt; // 创建Resource对象 Resource resource=new UrlResource(filePath); // 设置文件下载头 return ResponseEntity.ok() .header(Content-Disposition, attachment;filename= + fileName) .body(resource);}
三、注意事项
1.确保文件路径正确,避免文件不存在的情况。
2.设置正确的文件类型和内容长度。
3.使用try-with-resources语句确保资源被正确关闭。
四、总结
本文介绍了两种在Spring Boot中实现文件下载的方法:使用response输出流和使用ResponseEntity。两种方法各有优缺点,选择合适的方法取决于具体需求。目录
- 一、使用response输出流下载
- 二、使用ResponseEntity
- 三、注意
- 总结
一、使用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<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
@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):
<!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','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下载文件内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!

