Blob实现文件导出

import axios from 'axios';
import {
  getSessionStorage
} from './storage';

axios.defaults.headers = {
  'X-Requested-With': 'XMLHttpRequest'
};
axios.defaults.timeout = 1000 * 60 * 10;


function actionDownload(href, filename) {
  const aLink = document.createElement('a');
  aLink.href = href;
  aLink.style.display = 'none';
  if (filename) {
    aLink.setAttribute('download', filename);
  } else {
    aLink.download = '';
  }

  let event;
  if (window.MouseEvent) {
    event = new MouseEvent('click');
  } else {
    event = document.createEvent('MouseEvent');
    event.initMouseEvent(
      'click',
      true,
      false,
      window,
      0,
      0,
      0,
      0,
      0,
      false,
      false,
      false,
      false,
      0,
      null
    );
  }
  aLink.dispatchEvent(event);
  URL.revokeObjectURL(aLink.href);
}

function queryString(url, query) {
  const str = [];
  for (const key in query) {
    if (query[key]) {
      str.push(key + '=' + query[key]);
    }
  }
  str.push(`redomKey=${Math.random() * 1000}`); // 兼容IE,轮询调用同一接口(参数不变)

  const paramStr = str.join('&');
  return paramStr ?
    `${url}${url.indexOf('?') > -1 ? '&' : '?'}${paramStr}` :
    url;
}

function getHeaders(options) {
  const headers = Object.assign({
      'Content-Type': 'application/json'
    },
    options
  );

  const token = getSessionStorage('auth_token');
  if (token) {
    headers.Authorization = token;
  }
  return headers;
}

function directDownload(url, param) {
  const defaultParam = {};

  // 添加token权限验证
  const token = getSessionStorage('auth_token');
  if (token) {
    defaultParam.token = token;
  }

  Object.assign(defaultParam, param);

  // 手工转换encodeURI不能识别的字符
  let eurl = encodeURI(queryString(url, defaultParam));
  eurl = eurl.replace(/\+/g, '%2B');
  eurl = eurl.replace(/#/g, '%23');

  actionDownload(eurl);
}

function loadConfig(url, params, op, type) {
  let config = {
    method: 'get',
    url: queryString(url, params),
    headers: getHeaders(op)
  };
  if (type === 'post') {
    config = {
      method: 'post',
      url: url,
      data: params,
      headers: getHeaders(op)
    };
  }
  return config;
}

function resDownload(url, params, op, filename, type = 'get') {
  return new Promise((resolve, reject) => {
    axios({
      ...loadConfig(url, params, op, type),
      responseType: 'blob'
    }).then(
      (res) => {
        if (res.data) {
          if (filename === 'auto') {
            if (res.headers.fileName) {
               // 请求头里面有中文
              // 后台:response.setHeader("FileName", URLEncoder.encode(fileName, "UTF-8"));
              // 前台js:decodeURI(response.headers['filename'])
              filename = decodeURIComponent(res.headers.fileName);
            }
          }
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            // 是IE
            window.navigator.msSaveOrOpenBlob(new Blob([res.data]), filename);
          } else {
            actionDownload(
              window.URL.createObjectURL(new Blob([res.data])),
              filename
            );
          }
          resolve({});
        } else {
          resolve({
            error: {
              code: 500,
              message: '文件下载失败'
            }
          });
        }
      }
    );
  });
}

export default {
  download: function (url, params, filename, type, op) {
    if (filename) {
      return resDownload(url, params, op, filename, type);
    } else {
      directDownload(url, params);
    }
  },
  queryString
};

Blob对象
转载:https://www.jianshu.com/p/b322c2d5d778

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值