请求接口获取数据,并下载保存为文件
1,使用axios
const data = await axios({
method: 'get',// 设置请求方式
url: url1,// 设置请求地址
responseType: 'arraybuffer'
})
// data可能并不是blob数据流,可能是data.data
const blob = new Blob([data.data], { type: 'pdf'});
const filename = '123.pdf'
// 下载为文件
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement("a");
const body = document.querySelector("body");
link.href = window.URL.createObjectURL(blob); // 创建对象url
link.download = filename;
link.style.display = "none";
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href); // 通过调用 URL.createObjectURL() 创建的 URL 对象
}
2,不使用axios
xmlHttp.open("get",url1);
xmlHttp.send(null);
xmlHttp.responseType = "arraybuffer";
xmlHttp.onreadystatechange = () => {
//complete
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
console.log(xmlHttp.response);
if (typeof xmlHttp.response == "object") {
const data = xmlHttp.response;
const blob = new Blob([data], { type: 'pdf'});
let filename = '123.pdf';
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement("a");
const body = document.querySelector("body");
link.href = window.URL.createObjectURL(blob); // 创建对象url
link.download = filename;
link.style.display = "none";
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href); // 通过调用 URL.createObjectURL() 创建的 URL 对象
}
}
}
} else {
}
};
xmlHttp.onprogress = (event) => {
if (event.lengthComputable) {
var loaded = parseInt((event.loaded / event.total) * 100);
}
};