对于后端返回的文件流,前端如何下载?

61 阅读1分钟
  1. 封装下载文件的请求
// request.js
const downFile = (url, params = {}) =>request({
  url,
  method: 'get',
  responseType: 'blob',
  params,
});
export {downFile}
  1. api.js 文件下载的接口
import {downFile} from 'request.js'
export const downloadFile = (data = {}) => downFile('invoice/ossFile/download', data);
export default {downloadFile}
  1. 页面中下载文件功能的地方引入接口
    downloadOAFile.then((res) => {
    // 判断是否是json类型,是就抛出异常。反之,下载文件
     if (res.type === 'application/json') {
          let that = this;
          const fileReader = new FileReader();
          fileReader.readAsText(res, 'utf-8');
          fileReader.onload = function() {
            const data = JSON.parse(fileReader.result);
            that.$alert({
              type: 'warning',
              content: data.msg,
              showOkButton: false
            });
          };
        } else {
          this.saveAs(res, filename);
        }
})
  1. saveAs 前端实现下载功能
    saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        let link = document.createElement('a');
        let body = document.querySelector('body');
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        link.style.display = 'none';
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    },
  1. 若直接点击文件的url,进行下载。需要将url转为blob,再下载。
     downloadOAFile.then((res) => {
          this.getBlob(url, (blob) => {
          this.saveAs(blob, filename);
       });
     })
     getBlob(url, cb) {
       let xhr = new XMLHttpRequest();
       xhr.open('GET', url, true);
       xhr.responseType = 'blob';
       xhr.onload = function() {
         if (xhr.status === 200) {
           return cb(xhr.response);
         }
       };
       xhr.send();
     },