blob解决下载后端接口返回文件流乱码问题

1,516 阅读1分钟

[blob解决下载后端接口返回文件流乱码问题]

下载

封装调用接口方法
前端在发送请求时携带(responseType:‘blob’)
exportFileRequest(url,data) {
    return axios({
      method: 'post', //请求方式
      responseType: 'arraybuffer', // 请求数据返回方式
      // responseType: 'Blob',
      url: url, // 请求地址
      data: data, // 请求参数
      headers: {}, // 与后台定义的请求头参数
    });
  }
前端在发送请求时携带(responseType:‘blob’)
var token = sessionStorage.httpToken
axios.defaults.headers.common.token = token
axios({
  methods: 'GET',
  url: 'http://baidu.com'responseType: 'blob'
}).then(res => {
  let blob = new Blob([res.data], {type: 'application/xls'})
  let url = window.URL.createObjectURL(blob)
  // 重命名文件名称
  let a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('download', '123.xls')
  a.click()
})

调用

import * as util from "@/libs/util";

封装




export const createDownloadData = (res, fileName, fileType = 'doc') => {
  const Mime = {
      'doc': 'application/msword',
      'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'xls': 'application/vnd.ms-excel',
      'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  };
  var blob = new Blob([res], { type: Mime[fileType] });
  var objectUrl = URL.createObjectURL(blob);
  var a = document.createElement('a');
  document.body.appendChild(a);
  a.setAttribute('style', 'display:none');
  a.setAttribute('href', objectUrl);
  if (fileName) { a.setAttribute('download', fileName + '.' + fileType); };
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(objectUrl);
}