JS中利用a标签实现下载文件功能
export function downloadFile(path, name) {
const xhr = new XMLHttpRequest();
xhr.open("get", path);
xhr.responseType = "blob";
xhr.send();
xhr.onload = function($event) {
if ($event.target.status === 200) {
const url = URL.createObjectURL($event.target.response);
const a = document.createElement("a");
a.style.display = "none";
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
}
方式二:
export function downloadFile(path, name) {
const xhr = new XMLHttpRequest();
xhr.open("get", path);
xhr.send();
xhr.onload = function($event) {
if($event.target.status === 200) {
const blob = new Blob([this.response], {type: xhr.getResponseHeader('Content-Type')});
const url = URL.createObjectURL(blob);
const a = document.creatElement("a");
a.style.display = "none";
a.href = url;
a.download = name;
document.body.appendChildren(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
}
}