第一种方法下载文件(多文件时无法全部修改文件名称)
// 使用创建iframe标签的方式来下载文件
// 注意 1、 yourURl 是你要下载文件的链接路径
// 2、 ?response-content-type=application/octet-stream 这段拼的参数
//你也可以去掉看看能否下载,因为我的下载路径是 阿里的oss 需要带参数才能能实现下载,否则是线上预览功能,
//这里如果你的后端给你的路径已经做处理了那么你就不用带我这个参数了
var elemIF = document.createElement("iframe");
elemIF.src = `${yourURl}?response-content-type=application/octet-stream`;
elemIF.style.display = "none";
document.body.appendChild(elemIF);
// 3、使用iframe 方法能够实现多图片下载 放在for循环中
for(let attr in this.yourUrlList){
var elemIF = document.createElement("iframe");
elemIF.src = `${this.yourUrlList[attr]}?response-content-type=application/octet-stream`;
elemIF.style.display = "none";
document.body.appendChild(elemIF);
}
2、第二种方法实现文件下载并修改下载文件的名称
function getBlob(url, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (xhr.status === 200) {
cb(xhr.response);
}
};
xhr.send();
}
function saveAs(blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
var body = document.querySelector("body");
link.href = window.URL.createObjectURL(blob);
link.download = filename;
// fix Firefox
link.style.display = "none";
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
}
function download(url, filename) {
getBlob(url, function(blob) {
saveAs(blob, filename);
});
}
上述方法实现下载时只需要在 download(url,filename)中传入下载的路径及你定义的文件名称即可 ,在进行多文件下载时,把方法放到for循环里即可