14

I am currently trying to download the file from the s3 bucket using a button from the front-end. How is it possible to do this? I don't have any idea on how to start this thing. I have tried researching and researching, but no luck -- all I have searched are about UPLOADING files to the s3 bucket but not DOWNLOADING files. Thanks in advance.

NOTE: I am applying it to ReactJS (Frontend) and NodeJS (Backend) and also, the file is uploaded using Webmerge

UPDATE: I am trying to generate a download link with this (Tried node even if I'm not a backend dev) (lol)

see images below

what I have tried so far

onClick function

Jason Javier
  • 191
  • 1
  • 1
  • 8

2 Answers2

16

If the file you are trying to download is not public then you have to create a signed url to get that file.

The solution is here Javascript to download a file from amazon s3 bucket? for getting non public files, which revolves around creating a lambda function that will generate a signed url for you then use that url to download the file on button click

BUT if the file you are trying to download you is public then you don't need a signed url, you just need to know the path to the file, the urls are structured like: https://s3.amazonaws.com/ [file path]/[filename]

They is also aws amplify its created and maintain by AWS team.

Just follow Get started and downloading the file from your react app is simply as:

Storage.get('hello.png', {expires: 60})
.then(result => console.log(result))
.catch(err => console.log(err));
Tiisetso Tjabane
  • 2,088
  • 2
  • 19
  • 24
  • Great! Thanks :) – Jason Javier Sep 28 '18 at 10:53
  • Please do let me know how it goes and if my answer was any of help towards you I would I appreciated if I got an upvote or marked as the correct answer :) – Tiisetso Tjabane Sep 28 '18 at 11:04
  • It isn't as easy as logging to the console, because logging to the console is not getting the file downloaded to my users. I can't find any examples of how to actually get the link onto the page or downloaded to the user. It is a promise, so I have to wait on it, and can't just add it to a link tag... – Jake Jul 29 '20 at 21:14
13

Here is my solution:

let downloadImage = url => {
  let urlArray = url.split("/")
  let bucket = urlArray[3]
  let key = `${urlArray[4]}/${urlArray[5]}`
  let s3 = new AWS.S3({ params: { Bucket: bucket }})
  let params = {Bucket: bucket, Key: key}
  s3.getObject(params, (err, data) => {
    let blob=new Blob([data.Body], {type: data.ContentType});
    let link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download=url;
    link.click();
  })
}

The url in the argument refers to the url of the S3 file.

Just put this in the onClick method of your button. You will also need the AWS SDK

Jordan Daniels
  • 4,896
  • 1
  • 19
  • 29