axios读取blob文件
axios({
method: 'GET',
url: '/api/download',
params: {
reportRuleId: row.reportRuleId
},
responseType: 'blob'
}).then(response => {
if (response.data.type === 'application/octet-stream') {
const fileName = response.headers['content-disposition'].split('=')[1]
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
const blob = new Blob([response.data], { type: 'application/zip' })
window.navigator.msSaveOrOpenBlob(blob, fileName)
} else {
const blob = new Blob([response.data], { type: 'application/zip' })
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = fileName
link.click()
URL.revokeObjectURL(url)
}
resolve(response)
} else {
const reader = new FileReader()
reader.onload = function (event) {
const msg = JSON.parse(reader.result).data
_this.$errorMsg(message)
}
reader.readAsText(response.data)
}
}).catch(error => _this.$errorMsg(error))
fetch读取二进制文件
fetch(url, newOptions)
.then(res => res.blob())
.then(data => {
let downloadURL = window.URL.createObjectURL(data);
const a = document.createElement('a');
a.style.display = 'none';
a.href = downloadURL;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(downloadURL);
});
读取Blob文件的两种方式
- 从Blob中读取内容的方法是使用 FileReader。以下代码将 Blob 的内容作为类型数组读取:
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.addEventListener("loadend", function(result) {
});
- 使用Response对象。下述代码将Blob中的内容读取为文本:
var text = await (new Response(blob)).text();