axios并不支持这种下载请求,因此要使用使用 js-file-download 安装
npm install js-file-download
封装请求
import axios from "axios";
const service = axios.create({
responseType: 'arraybuffer'
})
service.interceptors.request.use(config => {
config.headers['Authorization'] = window.sessionStorage.getItem('tokenStr');
return config;
},error => {
alert(error);
})
service.interceptors.response.use(resp => {
const headers = resp.headers;
let reg = RegExp(/application\/json/);
if(headers['content-type'].match(reg)){
resp.data = unitToString(resp.data);
} else{
let fileDownLoad = require('js-file-download');
let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1];
let contentType = headers['content-type'];
fileName = decodeURIComponent(fileName);
fileDownLoad(resp.data,fileName,contentType);
}
},error => {
alert(error);
})
function unitToString(unitArr) {
let encodeStr = String.fromCharCode.apply(null,new Uint8Array(unitArr));
let decodeStr = decodeURIComponent(escape(encodeStr));
return JSON.parse(decodeStr);
}
let base = '';
export const downloadRequest = (url,params) => {
return service({
method: 'get',
url: `${base}${url}`,
data: params
});
}
export default service;
main.js引入
import {downloadRequest} from "./utils/download";
Vue.prototype.downloadRequest = downloadRequest
请求发起,直接调用传入请求的接口地址即可
exportData(){
this.downloadRequest('/employee/basic/export');
},
|