后端代码怎么写
示例:
第一种写法
1 2 3 4 5 6 7 8 9 10 11 12
|
@GetMapping("/download/file/{id}") public ResponseEntity<byte[]> downloadFle(@PathVariable String id) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("filename", "xxx.csv"); String content = "Hello World!"; return new ResponseEntity<>(content.getBytes(), headers, HttpStatus.OK); }
|
注意,返回 ResponseEntity<byte[]>,这里http响应返回的Body类型是byte数组,也就是我们写入到文件中的内容的字符数组表示。要想让浏览器知道我返回的内容你需要下载成文件给到访问者,就需要特定的告诉浏览器我返回的东西的格式是个文件而不是其他,这个是通过 setContentType 实现的。这个 ContentType 属性是 http 请求或响应的时候在 header 中携带的。如果是请求中携带,那就是告诉服务器我提交的数据的内容类型是什么,如果是响应中携带,那就是告诉浏览器我返回的数据的内容类型是什么。
如果不设置就会变成这样

设置之后,浏览器就知道你其实想要的是一个文件,而不是在浏览器中渲染了。

但是,我们下载下来的文件的名字好像不对。这个时候我们还需要告诉浏览器,下载的时候,文件的名字是什么呀
就是通过 headers.setContentDispositionFormData(“filename”, “xxx.csv”); 实现的
第二种写法,也是很久以前的写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
@GetMapping("/download/file2/{id}") public void downloadFle2(@PathVariable String id, HttpServletResponse httpServletResponse) throws IOException { String content = "Hello World!";
httpServletResponse.addHeader("Content-Length", String.valueOf(content.getBytes().length)); httpServletResponse.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE); httpServletResponse.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=xxx.csv"); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(httpServletResponse.getOutputStream()); bufferedOutputStream.write(content.getBytes()); bufferedOutputStream.flush(); }
|
前端代码怎么写