[blob解决下载后端接口返回文件流乱码问题]
下载
封装调用接口方法
前端在发送请求时携带(responseType:‘blob’)
exportFileRequest(url,data) {
return axios({
method: 'post',
responseType: 'arraybuffer',
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);
}