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