Answer the question
In order to leave comments, you need to log in
Is the delay before uploading files not working properly?
There is a loop that iterates over image links and sends them to the Download method (taken from StackOverflow), which causes the browser to download them.
function Download(url, name) {
fetch(url)
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = name;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})
.catch(() => alert("Ошибка загрузки файла"));
function DownloadWorker(url, name) {
setTimeout(function() {
Download(url, name);
}, DELAY);
}
Answer the question
In order to leave comments, you need to log in
Once:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function download(blob, name, url) {
const anchor = document.createElement("a");
anchor.setAttribute("download", name || "");
const blobUrl = URL.createObjectURL(blob);
anchor.href = blobUrl + (url ? ("#" + url) : "");
anchor.click();
setTimeout(() => URL.revokeObjectURL(blobUrl), 5000);
}
url
(third parameter) to blobUrl
, it may come in handy later - see where (from which link) the file was downloaded. blob:https://imgur.com/11fb6df9-e45b-4acf-b3eb-60d5d4656747#https://i.imgur.com/X92aA5Y.jpeg
for (const url of urls) {
const resp = await fetch(url);
const blob = await resp.blob();
const name = new URL(url).pathname.match(/[^\/]*$/)[0];
download(blob, name, url);
await sleep(200);
}
Your method is crooked. Use async / await if you want to download files sequentially:
async function downloadFiles(links) {
for (var n = 0; n < links.length; n++) {
try {
var blob = await (await fetch(links[n])).blob();
var blob_url = URL.createObjectURL(blob);
var blob_name = new URL(links[n]).pathname.split('/').pop();
var a = document.createElement('a');
a.style.display = 'none';
a.href = blob_url;
a.setAttribute('download', blob_name);
document.body.appendChild(a);
a.click();
console.log('Файл '+links[n]+' скачан');
// Делаем задержку на 2 секунды:
await new Promise(function(s) {
setTimeout(s, 2000);
});
URL.revokeObjectURL(blob_url);
}
catch(err) {
console.log('Ошибка, не удалось скачать файл ' + links[n]);
console.erroe(err);
// Делаем задержку на 2 секунды:
await new Promise(function(s) {
setTimeout(s, 2000);
});
}
}
console.log('Загрузка файлов завершена!');
}
downloadFiles([
'https://i.imgur.com/X92aA5Y.jpeg',
'https://i.imgur.com/X92aA5Y.jpeg',
'https://i.imgur.com/X92aA5Y.jpeg'
]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question