SpringBoot 接口输出文件流 & Vue 下载文件流,获取 Header 中的文件名

SpringBoot 接口输出文件流 & Vue 下载文件流,获取 Header 中的文件名

为什么浏览器中有些文件点击后是预览,有些是下载:https://www.cnblogs.com/vipsoft/p/18267174

Spring Boot 接口返回文件流 :https://www.cnblogs.com/vipsoft/p/16318030.html

@GetMapping("/download") 
public ResponseEntity<FileSystemResource> download(HttpServletRequest request) {
    File file = new File("D:\\VipSoft.zip");
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));   //如果是 attachment 换成 inline ,像PDF,图片这样的就可以在浏览器内直接预览了
    headers.add("filename",  URLEncoder.encode(file.getName(), "UTF-8"));
    headers.add("Access-Control-Expose-Headers", "filename");  //这个要加,否则Vue 在 res.headers['filename'] 时取不到值
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    headers.add("Last-Modified", new Date().toString());
    headers.add("ETag", String.valueOf(System.currentTimeMillis()));
    return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
}

Vue 中获取不到 后面传的 header 是因为少加了 "Access-Control-Expose-Headers"

instance.interceptors.response.use(
  response => {
    if (response.status >= 200 && response.status < 300) {
        var blob = new Blob([response.data], {type: 'application/octet-stream'});
        var downloadElement = document.createElement('a');
        var href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = filename; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      return response.data
    } else {
      Message({
        message: '请求错误' + response.status,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(response)
    }
  },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

 

posted @ 2022-09-06 17:50  VipSoft  阅读(3061)  评论(0编辑  收藏  举报