downLoadBlob(url: string) {
return new Promise((resolve: (blob: any) => void, reject: () => void) => {
const xhr = new XMLHttpRequest();
// url oss地址
xhr.open("get", url, true);
// 响应方式
xhr.responseType = "blob";
xhr.onload = function () {
console.log(this);
if (this.status == 200 && this.readyState === 4) {
const blob = this.response;
resolve({ code: 200, blob });
} else {
resolve({ code: 500, msg: this.response.msg || "下载失败" });
}
};
xhr.send(); // 发送请求
xhr.onerror = function () {
resolve({ code: 500, msg: this.response.msg || "下载失败" });
};
});
}
//触发下載 url 是 oss地址
async downFile(url) {
const res = await this.downLoadBlob(url);
if (res.code === 200) {
let save_link = document.createElement("a");
/*
URL.createObjectURL() 静态方法会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。
这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
*/
save_link.href = window.URL.createObjectURL(res.blob);
save_link.download = '重命名';
save_link.click();
} else {
this.$message.error(res.msg);
}
}
注意:oss 地址请求会跨域。需要加入白名单。