以下方法是后台返回文件流(从文件头里取类型,可下载任何类型的文件)
接口请求
下载一般类型:
/**
* download file下载文件
*/
export const downloadBlobFile = (res, fileNameS) => {
if (!res) {
return
}
let contentType = res.headers['content-type'];
const blob = new Blob([res.data], {
type: contentType
})
let fileName = ''
if(fileNameS) {
fileName = `${fileNameS}`
} else {
fileName = res.headers['content-disposition'] ? decodeURI(escape(res.headers['content-disposition'].split(';')[1].split('=')[1])) : '';
}
debugger
let a = document.createElement("a");
let url = window.URL.createObjectURL(blob);
console.log(blob)
a.setAttribute("href", url)
a.download = fileName
document.body.appendChild(a);
a.click()
document.body.removeChild(a);
}
下载blobjson类型:
// 下载bolbjson
export const downloadBlobJson = (data, fileNameS = 'json') => {
if (!data) {
return
}
// console.log(data)
const blob = new Blob([JSON.stringify(data)])
const fileName = `${fileNameS}.json`
if ('download' in document.createElement('a')) { // 不是IE浏览器
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link) // 下载完成移除元素
window.URL.revokeObjectURL(url) // 释放掉blob对象
} else { // IE 10+
window.navigator.msSaveBlob(blob, fileName)
}
}
以下方法是后台返回文件地址
一般文件的导出:
/**
* @param attachPath 导出路径
* @return 导出文件
*/
export const downloadFile =(attachPath)=> {
var $a = document.createElement('a');
$a.setAttribute("href", attachPath);
$a.setAttribute("download", "");
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
$a.dispatchEvent(evObj);
}
跨域文件导出下载方法
/**
* @param url 导出路径
* @param fileName 文件名
* @return 跨域文件路径、下载到本地的文件名
*/
export const downloadFileBlob =(url,fileName)=> {
var x = new XMLHttpRequest();
x.open("GET", url, true);
x.responseType = 'blob';
x.onload=function(e) {
var url = window.URL.createObjectURL(x.response)
var a = document.createElement('a');
a.href = url
a.download = fileName;
a.click()
}
x.send();
}