0

I'm quite confused on how to use the Amplify library to actually download an mp3 file stored in my s3 bucket. I am able to list the bucket contents and parse it all out into a tree viewer for users to browse the various files, but once I select a file I can't get it to trigger a download.

I'm confident my amplify configuration is correct since I can see all my expected directories and when I select the file I want to download, I see the response size being correct: chome network tab

You can see it takes 2+ seconds and appears to be downloading the data/mp3 file, but the user is never prompted to save the file and it's not in my Downloads folder.

Here is a capture of my file metadata setup from my bucket: file metadata

And the method I'm calling:

  getFile (fileKey) {
      Storage.get(fileKey, {download: true})
  }

Without the "download : true" configuration, I get the verified URL back in the response. I'd like to avoid making a 2nd request using that URL download the file if possible. Anything else I may have missed? Is it better for s3 operations to go back to the standard aws-sdk? Thanks in advance!

egoess
  • 11
  • 3

1 Answers1

0

I ended up using a combination of this answer: https://stackoverflow.com/a/36894564

and this snippet: https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743

So the file gets downloaded in the response data(result), I added more meta data tags to the files to get the file name and title. Finally adding the link to the DOM and executing a click() on it saves the file named correctly. Full solution below:

getFile (fileKey) {
      Storage.get(fileKey, {download: true}).then(result => {
        console.log(result)
        let mimeType = result.ContentType

        let fileName = result.Metadata.filename
        if (mimeType !== 'audio/mp3') {
          throw new TypeError("Unexpected MIME Type")
        }

        try {
          let blob = new Blob([result.Body], {type: mimeType})

          //downloading the file depends on the browser
          //IE handles it differently than chrome/webkit
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, fileName)
          } else {
            let objectUrl = URL.createObjectURL(blob);
            let link = document.createElement('a')
            link.href = objectUrl
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        } catch (exc) {
          console.log("Save Blob method failed with the following exception.");
          console.log(exc);
        }

      })
  }
} 
egoess
  • 11
  • 3