在这里我不过多介绍每行代码是什么意思。会用就行了
vue axios 操作
export function downLoad(data){
return request({
url: `/home/file/download/brand`,
method: 'GET',
params:data,
responseType:'blob',
})
}
derive(number){//导出W
let str = number==0?'.xlsx':'.csv'
let name = this.$route.meta.title
API.downLoad({type:number}).then((res)=>{
let url = URL.createObjectURL(new Blob([res]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', name+'下载'+ str)
document.body.appendChild(link)
link.click()
URL.revokeObjectURL()
})
}
原生方法
fileDeal = (type: string, id: string, name: string) => {
const client = new XMLHttpRequest();
const _url = `${apiUrl}/oss/object/download?objectId=${id}`
client.open("GET", _url, true)
client.setRequestHeader('Content-Type', 'application/json');
client.setRequestHeader("Authorization", `bearer ${sessionStorage.token}`);
client.responseType = 'blob'
client.send()
client.onreadystatechange = function () {
if (client.readyState == 4 && client.status == 200) {
if (type === 'download') {
// 下载
const reader = new FileReader();
reader.readAsDataURL(client.response);
reader.onload = (e: any) => {
console.log(e)
const a = document.createElement('a');
a.download = decodeURIComponent(name);
a.href = e.target.result;
a.target = "_blank"
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
} else {
// 预览
let blob = new Blob([client.response], {
type: 'application/pdf;chartset=UTF-8'
});
let fileURL = URL.createObjectURL(blob);
window.open(fileURL);
}
}
}
}
原生下载压缩包
import {saveAs} from "file-saver"; 这是一个插件里面做的事无非就事创建a标签,然后点击最后删掉a标签
const apiUrl = `${ENV.APIROOT}/${ENV.APIVERSION}`;
const client = new XMLHttpRequest();
const _url = apiUrl+`/downloadCompress/${id}`
client.open("GET", _url, true)
client.setRequestHeader('Content-Type', 'application/json');
client.setRequestHeader("Authorization", `bearer ${sessionStorage.token}`);
client.responseType = 'blob'
client.send()
client.onreadystatechange = function () {
if (client.readyState == 4 && client.status == 200) {
console.log(client)
let fileName:any = decodeURIComponent(client.getResponseHeader('Content-disposition') || '').split('filename=')[ 1 ]
saveAs(client.response, fileName);
}
if (client.readyState === 4 && client.status === 200) {
let name: any = exportName ? `${exportName}.xlsx` : "导出.xlsx";
const headerName = client.getResponseHeader("Content-disposition");
console.log("headerName", headerName, client.response);
if (headerName) {
const nameIndex = headerName.lastIndexOf("=");
name = nameIndex !== -1 && headerName.substring(nameIndex + 1);
}
window.saveAs(client.response, decodeURIComponent(name));
}
}
其实这里我有不同的观点,其实有简便的方法,我们普通的下载也可以用saveAs(client.response,fileName)
这个插件就是file-saver
https://github.com/eligrey/FileSaver.js/blob/master/src/FileSaver.js 源码基于base64
vue axios下载压缩包
API.exportGoodsPosition(param).then((res)=>{
let str = res.headers['content-disposition']
let name = str.split('=')[1]
let url = window.URL.createObjectURL(new Blob([res.data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', decodeURIComponent(name))
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(url)
document.body.removeChild(link);
})
此外还有很多可以复用的ts写法,即使写法有很多但是都大同小异。如下
exportStream(url, params)
.then((res: any) => {
that.setState({ [`${loadingFiled}`]: false });
let bolb: Blob = new Blob([res]);
let a: HTMLAnchorElement = document.createElement("a");
let url: string = window.URL.createObjectURL(bolb);
a.setAttribute("href", url);
a.setAttribute("download", `${name}.xlsx`);
a.click();
URL.revokeObjectURL(url);
})
此外还给大家普及下 XMLHttpRequest上面的方法 abort getAllResponseHeaders getResponseHeader open send setRequestHeader overRideMimeType upload