0


springboot:各种下载文件的方式

文章目录

springboot:各种下载文件的方式

一、使用response输出流下载

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

@GetMapping("/t1")publicvoiddown1(HttpServletResponse response)throwsException{
        response.reset();
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-disposition","attachment; filename=test.png");try(BufferedInputStream bis =newBufferedInputStream(newFileInputStream("E:\\desktop\\1.png"));// 输出流BufferedOutputStream bos =newBufferedOutputStream(response.getOutputStream());){byte[] buff =newbyte[1024];int len =0;while((len = bis.read(buff))>0){
                bos.write(buff,0, len);}}}

二、使用ResponseEntity

@GetMapping("/t2")publicResponseEntity<InputStreamResource>down2()throwsException{InputStreamResource isr =newInputStreamResource(newFileInputStream("E:\\desktop\\1.png"));returnResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).header("Content-disposition","attachment; filename=test1.png").body(isr);}@GetMapping("/t3")publicResponseEntity<ByteArrayResource>down3()throwsException{byte[] bytes =Files.readAllBytes(newFile("E:\\desktop\\1.png").toPath());ByteArrayResource bar =newByteArrayResource(bytes);returnResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).header("Content-disposition","attachment; filename=test2.png").body(bar);}

三、注意

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

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

@PostMapping("/t4")publicResponseEntity<ByteArrayResource>down4(String fileName,@RequestBodyMap data)throwsException{System.out.println(data);byte[] bytes =Files.readAllBytes(newFile("E:\\desktop\\1.png").toPath());ByteArrayResource bar =newByteArrayResource(bytes);returnResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).header("Content-disposition","attachment; filename=test.png").body(bar);}

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

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><script>functiondownload(){var ajax =newXMLHttpRequest();
        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><inputtype="button"value="下载"onclick="download();"/></body></html>
标签: spring boot java 前端

本文转载自: https://blog.csdn.net/weixin_43296313/article/details/125100824
版权归原作者 yololee_ 所有, 如有侵权,请联系我们删除。

“springboot:各种下载文件的方式”的评论:

还没有评论