Download Multiple Files with JavaScript and Anchor Element
To download files with JavaScript, simply create an anchor element, set href
and download
attributes, and click the element. Calling the following function will download an empty text file encoded in utf-8
named blank.txt
.
const downloadFileWithAnchor = () => {
const anchor = document.createElement("a");
anchor.href = "data:text/plain;charset=utf-8,";
anchor.download = 'blank.txt';
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
};
Multiple files can be downloaded at once by calling downloadFileWithAnchor
function multiple times. In the following example, 100 files are downloaded consecutively in macOS Safari. It works on Chromium and Firefox as well.
However, when downloadFileWithAnchor
is called over 10 times in Google Chrome, only 10 files are downloaded. The function itself is called over 10 times — it’s just that Chrome limits simultaneous download requests.
Solution
Add delays between each downloadFileWithAnchor
call. Setting timeouts by index * 200ms
worked even on large files that which are over 500MB
each.
const repeatCount = 20;for (let i = 0; i < repeatCount; i += 1) {
setTimeout(
() => {
downloadFileWithAnchor("periodic");
},
i * 200 // Delay download every 200ms
);
}
Example
Demo and its source code is provided in CodePen.