Couldn't download several files Programmatically through <a> tag

My node server sends links to the client to download by creating tag and triggering it. But that way I am able to download only one file .

My handleDownload function:

 //imageUrls is a array containing links
 function handleDownload(){
  for(let i=0;i<imageUrls.length;i++){

My downloadAnImage function:

 function downloadAnImage(imageLink){
  let link=document.createElement('a');
  link.href = process.env.REACT_APP_PROXY+"/download/"+imageLink = imageLink;;

By the way, only the last link of the array gets downloaded . Thanks in advance!

Please correct me if I am wrong here…

Not exactly sure, but it seems like it’s because you aren’t storing all of them, just iterating through indexes in the for loop, so the value will be the last link it downloaded?

In your code snippets, I don’t see where it is pushing, slicing, unshifting , mapping or anything like that to a declared empty array like myLinks = []; or something, so I’m assuming it is just returning the last link that it downloaded. (Iterating through but not storing each on the client side?).

Maybe you are doing that somewhere, but didn’t post that part?

Or maybe I am misunderstanding.

I have tried to make an array containing all the “a” tags and then iterate through it and run But same result

function handleDownload(){
      for(let i=0;i<imageUrls.length;i++){
      //after downloading all the images clears imageUrl and images state

    // downloads an image from the server
     function createLink(imageLink){
      let link=document.createElement('a');
      link.href = process.env.REACT_APP_PROXY+"/download/"+imageLink = imageLink;
        return prevState;
     // console.log(downloadLinks)

    function clickLinksToDownload(){


I see what you are trying to do. I tried to simulate your environment and get your code working. I cannot even get just the last link.

If I do something like this:

let mySite = "";
let images = ["atD3CjJ.jpg", "XoabeiI.jpg", "qApzaRV.jpg", "1LoxabT.jpg", "4bdJapA.jpg"];

function myFunction(Site, imgArr) {
  for (let i = 0; i < imgArr.length; i++) {
    let url = mySite + imgArr[i];
    let a = document.createElement("a");
    a.href = url; = imgArr[i];, '_blank');
myFunction(mySite, images);

I can get 5 tabs to open with each picture in a separate tab.

But it sounds like you wanted it to actually download each file, not display each image in it’s own tab.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.