JS批量下載圖片或文件(V2,已詳細解說)
目標
例如,你在網(wǎng)上,看到某個網(wǎng)頁可以下載很多圖片資源,但是沒有批量下載怎么辦?于是,幻想有這么個函數(shù) downloadImages(imageURLs)
批量下載。咋整?
方案
解決下載問題
一般情況下,用 <a>
標簽可以實現(xiàn)文件的下載功能。一般下載是這樣的代碼:
<a href="/path/to/receipt.pdf" download>下載</a>
如此,點擊下載,即可顯示下載,此時文件名跟原名一樣receipt.pdf。
download
屬性配置目標文件(就是href
屬性指定的文件 )將被執(zhí)行下載操作。
download
的可配置一個值,作為下載后的文件名。如果文件名沒有限制,那么瀏覽器將自動檢測當前文件的擴展名并添加到文件上 (.img, .pdf, .txt, .html, 等等)如果沒有配置一個值,原始文件名將被用上。
下邊這種情況指定文件名。
<a href="/path/to/receipt.pdf" download="收據(jù)">下載</a>
如此,點擊下載,即可顯示下載并且文件名為收據(jù).pdf。
解決下載圖片時總是預(yù)覽的問題
你可能已經(jīng)意識到,上邊的的這個方式對圖片無法達到真正的下載,而是單純的預(yù)覽。應(yīng)該怎么做呢?
我們可以通過將圖片的二進制信息以Blob對象的方式存儲,將其轉(zhuǎn)換為URL對象,再讓 <a>
來下載它。
-
fetch(imgUrl).then(res => blob())
來獲取圖片二進制信息 -
URL.createObjectURL(blob)
來創(chuàng)建圖片的 URL 對象 -
document.createElement("a")
來創(chuàng)建下載鏈接對象 -
<a href="{url}" download>
來重新指向需要下載的圖片資源 - 點擊下載即可
- 清理創(chuàng)建的對象即可(URL、下載鏈接)
function downloadImage(filename, url) {
fetch(url)
.then((res) => res.blob())
.then((blob) => {
// create URL and Link
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
// Invoke download
a.click();
// remove URL and Link
window.URL.revokeObjectURL(url);
a.remove();
})
.catch((err) => console.error(err.message));
}
// 已下載的文件名為"new-filename.jpg"
downloadImage('new-filename', 'path/or/url/to/your/image.jpg')
注意下載圖片的時候,最好是在圖片URL相同的域名之下,否則很多圖片是禁止跨域訪問的。
解決批量問題
這里不是批量下載如何寫循環(huán)的問題,而是
- 因為程序太快然而下載太慢所導(dǎo)致的一系列問題
我們就簡化處理,一秒鐘讓它發(fā)送一個下載圖片的請求。
for (let i=0; i<urls.length; i++) {
setTimeout(() => {
// codes for downloading an image
}, i*1000)
}
總結(jié)代碼
“Talk is cheap, show you the code”:
function downloadImage(filename, url) {
fetch(url)
.then((res) => res.blob())
.then((blob) => {
// create URL and Link
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
// Invoke download
a.click();
// remove URL and Link
window.URL.revokeObjectURL(url);
a.remove();
})
.catch((err) => console.error(err.message));
}
function downloadImages(urls) {
for (let i = 0; i < urls.length; i++) {
setTimeout(() => {
// codes for downloading an image
downloadImage(`${Date.now()}`, urls[i]);
}, i * 1000);
}
}
// download two images for example
downloadImages(["/path/to/image1.jpg", "/path/to/image2.png"]);
搞定,收功。文章來源:http://www.zghlxwxcb.cn/news/detail-475151.html
創(chuàng)作不易,請多珍惜。文章來源地址http://www.zghlxwxcb.cn/news/detail-475151.html
到了這里,關(guān)于JS批量下載圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!