JS通过URL下载文件并重命名两种方式代码
作者:訾博ZiBo
前端下载文件方法很多,url是文件地址,下面这篇文章主要给大家介绍了关于JS通过URL下载文件并重命名的两种方式,文中通过代码介绍的非常详细,需要的朋友可以参考下
一、a 标签简单设置 href 方式
// 下载文件
function downloadFile() {
const link = document.createElement('a');
link.style.display = 'none';
// 设置下载地址
link.setAttribute('href', file.sourceUrl);
// 设置文件名
link.setAttribute('download', file.fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
二、a 标签使用 blob 数据类型方式
async function download(downloadUrl: string, downloadFileName: string ) {
const blob = await getBlob(downloadUrl);
saveAs(blob, downloadFileName );
}
function getBlob(url: string) {
return new Promise<Blob>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(new Error(`Request failed with status ${xhr.status}`));
}
};
xhr.onerror = () => {
reject(new Error('Request failed'));
};
xhr.send();
});
}
function saveAs(blob: Blob, filename: string) {
const link = document.createElement('a');
const body = document.body;
link.href = window.URL.createObjectURL(blob);
link.download = filename;
// hide the link
link.style.display = 'none';
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}附:通过blob实现跨域下载并修改文件名
点击时调用如下方法
function load(file) {
this.getBlob(file.url).then(blob => {
this.saveAs(blob, file.name);
});
},//通过文件下载url拿到对应的blob对象
getBlob(url) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
},//下载文件
saveAs(blob, filename) {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
}总结
到此这篇关于JS通过URL下载文件并重命名两种方式的文章就介绍到这了,更多相关JS URL下载文件并重命名内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
