大家好,我正在嘗試下載我在我的 react 應用程式上顯示的影像。該應用程式從 API 獲取影像并將它們顯示在網頁上,并將 img src 存盤在一個陣列中。我正在嘗試制作一個下載按鈕,該按鈕將遍歷我的 src 陣列并下載所有顯示的影像并需要一些指導。我已經閱讀了許多以前的帖子,并意識到我無法在我的 react 應用程式中使用 cURL,并且 fetch API 不會下載影像。我想看看是否有辦法用 Javascript 來做到這一點,或者是否有另一種編程語言的簡單替代方案。謝謝您的幫助!
const downloadAll = () => {
const imgArr = document.querySelectorAll('img');
for (let i = 0; i < imgArr.length; i ) {
let a = imgArr[i].src;
}
};
uj5u.com熱心網友回復:
使用download錨的屬性應該可以解決問題......
編輯
下載僅適用于同源 URL 或 blob: 和 data: 方案。參考
由于這不是您的情況,因此您必須為每個影像創建一個 blob,幸運的是,使用fetchAPI 很容易。
const downloadAll = async () => {
// Create and append a link
let link = document.createElement("a");
document.documentElement.append(link);
const imgArr = document.querySelectorAll("img");
for (let i = 0; i < imgArr.length; i ) {
await fetch(imgArr[i].src)
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {
let objectURL = URL.createObjectURL(blob);
// Set the download name and href
link.setAttribute("download", `image_${i}.jpg`);
link.href = objectURL;
// Auto click the link
link.click();
})
}
};
在CodePen上測驗。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/415766.html
標籤:
