简体   繁体   中英

Download S3 file from pre-signed URL without popup blocker

I have a Meteor application where I'm downloading files from S3 using pre-signed URLs (need to be generated with an API call).

I was having an issue with popup blockers preventing a new tab from opening with the url generated by the AWS-SDK so I changed my code to the following:

downloadDocument(document, event) {
    // open tab immediately to prevent popup blocker
    const myNewTab = window.open();

    // call method to generate url
    Meteor.call('Events.Methods.Document.Download', { key: document.key, eventId: event._id }, (error, res) => {
      if (error) { ... } // removed handle error code

      // if url generated, set tab location to url
      if (res) myNewTab.location.href = res;

      // auto close the tab after 1 second
      myNewTab.setTimeout(() => { myNewTab.close(); }, 1000);
    });
}

This code is working for the most part but it doesn't feel very clean. Also if the API call ever takes more than 1 second (slow inte.net) then the tab will close before the download begins

How can I change this so that I can wait for the download to happen, before closing the tab? Or a similar solution that would result in me ensuring the downloads always go through without popup blockers being an issue?

Thanks

You are always going to run afoul of pop-up blockers if you open a new window.

What you should do is generate an <a href="my-custom-server-generated-url" download> link with the download property, which will force a download without needing a new window.

Then you also don't need to close the window on a timer (which wasn't a good approach in the first place)

This was happening only in Safari, so we switched to always downloading the file instead of opening in a new window in Safari/mobile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM