Home » Javascript » How can I download a group of files with a element use javascript?

How can I download a group of files with a element use javascript?

Posted by: admin June 30, 2018 Leave a comment

Questions:

consider the following code:

I have a button on the page that when I click it, it will download the images.

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Download</title>
</head>

<body>
    <button onclick="handleDownload()">download</button>

    <script> 
        // Assume these urls are valid and can been downloaded in the 
           same domain
        var urls = ['url1', 'url2', 'url3'];

        function handleDownload() {
            for (var url of urls) {
                var a = document.createElement('a');
                a.setAttribute('href', url);
                a.setAttribute('download', '-');
                a.click();
            }
        }
    </script>
</body>

</html>

The question is when I click the download button, it send all request but just download one image, so I don’t know what’s the problem.

Is the a.click() execute too fast or other cause?

Answers: