5

I'm trying to do what I 'thought' would be a simple task. I have an array of URLs that I'd like to loop through and download on to the client machine when the user clicks a button.

Right now I have a parent component that contains the button and an array of the urls (in the state) that I'd like to loop through and download. For some reason, the way I'm doing it now only downloads one of the files, not all of the contents of the array.

Any idea how to do this correctly within React?

handleDownload(event){
        var downloadUrls = this.state.downloadUrls;
        downloadUrls.forEach(function (value) {
            console.log('yo '+value)
        const response = {
              file: value,
        };                
            window.location.href = response.file;

        })
    }
3
  • why are you calling slice on downloadUrls? Commented May 2, 2017 at 23:59
  • Because I have an array of URLs in my state. downloadUrls = ["file1", "file2", "file3"]. Users are able to select checkboxes of files that they would like to download before clicking the parent "Download all selected" button. Commented May 3, 2017 at 1:03
  • thats not an answer. what is the use or the point of calling slice? what are you trying to accomplish there? Commented May 3, 2017 at 1:49

1 Answer 1

2

I would use setTimeout to wait a little bit between downloading each files.

handleDownload(event){
    var downloadUrls = this.state.downloadUrls.slice();
    downloadUrls.forEach(function (value, idx) {
        const response = {
          file: value,
        };
        setTimeout(() => {
            window.location.href = response.file;
        }, idx * 100)
    })
}

In Chrome, this will also prompt the permission asking for multiple files download.

Sign up to request clarification or add additional context in comments.

1 Comment

If URLs can be opened in a browser, this solution would open them instead of downloading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.