JS通過URL下載文件并重命名兩種方式代碼
更新時間:2023年11月01日 12:01:25 作者:訾博ZiBo
前端下載文件方法很多,url是文件地址,下面這篇文章主要給大家介紹了關(guān)于JS通過URL下載文件并重命名的兩種方式,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
一、a 標(biāo)簽簡單設(shè)置 href 方式
// 下載文件
function downloadFile() {
const link = document.createElement('a');
link.style.display = 'none';
// 設(shè)置下載地址
link.setAttribute('href', file.sourceUrl);
// 設(shè)置文件名
link.setAttribute('download', file.fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
二、a 標(biāo)簽使用 blob 數(shù)據(jù)類型方式
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實(shí)現(xiàn)跨域下載并修改文件名
點(diǎn)擊時調(diào)用如下方法
function load(file) {
this.getBlob(file.url).then(blob => {
this.saveAs(blob, file.name);
});
},//通過文件下載url拿到對應(yīng)的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();
}總結(jié)
到此這篇關(guān)于JS通過URL下載文件并重命名兩種方式的文章就介紹到這了,更多相關(guān)JS URL下載文件并重命名內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
js字符串日期yyyy-MM-dd轉(zhuǎn)化為date示例代碼
獲取表單中的日期往后臺通過json方式傳的時候,遇到Date.parse(str)函數(shù)在ff下報錯,有類似情況的朋友可以參考下本文2014-03-03
淺談JS for循環(huán)中使用break和continue的區(qū)別
這篇文章主要介紹了淺談for循環(huán)中使用break和continue的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
JS實(shí)現(xiàn)移動端整屏滑動的實(shí)例代碼
本文通過實(shí)例代碼給大家分享了基于js 實(shí)現(xiàn)移動端整屏滑動效果,基本思路是檢測手指滑動方向,獲取手指抬起時的位置,減去手指按下時的位置,得正即為向下滑動了,具體實(shí)現(xiàn)代碼大家參考下本文2017-11-11
javascript Deferred和遞歸次數(shù)限制實(shí)例
你知道Deferred和遞歸次數(shù)限制嗎?如果還不知道,可以看看下面的實(shí)例,很好,適合新手朋友們2014-10-10

