数据流格式
if (response && response.config && response.config.responseType == 'blob') {
// 开始处理文件下载 - res.data为文件流
let blobUrl = window.URL.createObjectURL(new Blob([response.data], {
// 后台传递的文件类型 - 此处我是直接写死的
// 也可以从后台获取的
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}));
const link = document.createElement('a');
link.style.display = 'none';
link.href = blobUrl;
const dis = response.headers['content-disposition']
const filenameKey = 'filename='
const indexOf = dis.indexOf(filenameKey)
const filename = indexOf ? decodeURI(dis.substring(indexOf + filenameKey.length)) : '未知文件名'
// fileName 文件的名称
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
下载url格式
let link = document.createElement('a')
link.href = this.fileUrl (需要下载的文件url)
link.click()
相关:常见文件类型格式
常见文件类型格式:
// .xls: application/vnd.ms-excel
// .xlsx: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
// .txt: text/plain
//: .png/.jpg/etc:image/*
//.htm,.html: text/html
//.avi, .mpg, .mpeg, .mp4: video/*
//.mp3, .wav, etc: audio/*
//PDF: .pdf
相关:获取response header数据
在下载文件时,大多需要根据后端返回动态获取文件格式或者文件名等
let req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
let headers = req.getAllResponseHeaders().toLowerCase();
console.log(headers);
// 由于返回的是用\r\n来进行分割的字符串,需要做转换
let arr = headers.trim().split(/[\r\n]+/);
let headerMap = {};
arr.forEach(function (line) {
let parts = line.split(': ')
let header = parts.shift()
let value = parts.join(': ')
headerMap[header] = value
})
let contentType = headerMap['content-type'];
console.log('contentType: ', content-type);