Categories
JavaScript Answers

How to let a user download multiple files when a button is clicked with JavaScript?

Spread the love

Sometimes, we want to let a user download multiple files when a button is clicked with JavaScript.

In this article, we’ll look at how to let a user download multiple files when a button is clicked with JavaScript.

How to let a user download multiple files when a button is clicked with JavaScript?

To let a user download multiple files when a button is clicked with JavaScript, we create a link to the file to download and then click it.

For instance, we write

const urls = [
  "http://example.com/file1",
  "http://example.com/file2",
  "http://example.com/file3",
];

const download = async (urls) => {
  for (const url of urls) {
    const a = document.createElement("a");
    a.setAttribute("href", url);
    a.setAttribute("download", "");
    a.setAttribute("target", "_blank");
    a.click();
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
};

to loop through the url in urls in the download function with a for-of loop.

In it, we create a link with createElement.

Then we set the href attribute to the file url with setAttribute.

Next we call click to click on the link to start the download.

Then we use await on the promise to pause the function for 1 second with setTimeout.

Conclusion

To let a user download multiple files when a button is clicked with JavaScript, we create a link to the file to download and then click it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *