react項(xiàng)目中遇到前端在處理后端傳來(lái)的文件流實(shí)現(xiàn)導(dǎo)出Excel文件功能,responseType:'blob'類型設(shè)置無(wú)效問(wèn)題揩懒。
axios請(qǐng)求設(shè)置responseType: 'blob' 返回類型
const axios = require('axios');
export() {
const token = sessionStorage.getItem('token');
axios({
method: 'post',
url: `/list/downXlsx`, // 請(qǐng)求地址
data,
responseType: 'blob', // 表明返回服務(wù)器返回的數(shù)據(jù)類型 這里注意要加上responseType
headers: {
Authorization: `Bearer${token}`
}
}).then((res) => { // 處理返回的文件流
const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
const fileName = 'down.xlsx'
const alink = document.createElement('a')
alink.download = fileName
alink.style.display = 'none'
alink.href = URL.createObjectURL(blob) // 這里是將文件流轉(zhuǎn)化為一個(gè)文件地址
document.body.appendChild(alink)
alink.click()
URL.revokeObjectURL(alink.href) // 釋放URL 對(duì)象
document.body.removeChild(alink)
})
}
打印發(fā)現(xiàn)res.data返回是字符串亂碼,并沒(méi)有轉(zhuǎn)換blob類型
20200215165621.png
于是各種找坑路上發(fā)現(xiàn)挽封,原來(lái)在項(xiàng)目中使用了mockjs來(lái)模擬接口已球,mockjs初始化的時(shí)候給攔截響應(yīng)設(shè)置了responseType:''
mockjs源碼
// 初始化 Response 相關(guān)的屬性和方法
Util.extend(MockXMLHttpRequest.prototype, {
responseURL: '',
status: MockXMLHttpRequest.UNSENT,
statusText: '',
// https://xhr.spec.whatwg.org/#the-getresponseheader()-method
getResponseHeader: function(name) {
// 原生 XHR
if (!this.match) {
return this.custom.xhr.getResponseHeader(name)
}
// 攔截 XHR
return this.custom.responseHeaders[name.toLowerCase()]
},
// https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method
// http://www.utf8-chartable.de/
getAllResponseHeaders: function() {
// 原生 XHR
if (!this.match) {
return this.custom.xhr.getAllResponseHeaders()
}
// 攔截 XHR
var responseHeaders = this.custom.responseHeaders
var headers = ''
for (var h in responseHeaders) {
if (!responseHeaders.hasOwnProperty(h)) continue
headers += h + ': ' + responseHeaders[h] + '\r\n'
}
return headers
},
overrideMimeType: function( /*mime*/ ) {},
responseType: '', // '', 'text', 'arraybuffer', 'blob', 'document', 'json'
response: null,
responseText: '',
responseXML: null
})
找到入口文件把require('./mock/index.js');注釋就可以了~
企業(yè)微信截圖_15817568349106.png
爬坑路上好辛苦!哈哈哈哈~