Javascript to download a file from amazon s3 bucket?

I tried to upload a file from a bucket on Amazon S3. I was wondering if I could write javascript to load such a file from a bucket. I searched for it, but could not find any resources that could help me with this.

Some of these steps are: authenticating Amazon S3, then providing the name of the bucket and file (key), downloading or reading the file so that I can display the data in the file.

Thanks,

+13
javascript amazon-s3 amazon-web-services download
source share
3 answers

Maybe you can use AWS Node.js API :

var AWS = require('aws-sdk'); AWS.config.update( { accessKeyId: ".. your key ..", secretAccessKey: ".. your secret key ..", } ); var s3 = new AWS.S3(); s3.getObject( { Bucket: "my-bucket", Key: "my-picture.jpg" }, function (error, data) { if (error != null) { alert("Failed to retrieve an object: " + error); } else { alert("Loaded " + data.ContentLength + " bytes"); // do something with data.Body } } ); 
+24
source share

I came here looking to download the s3 file on the client side. Here's how I solved it:

Since I cannot store my s3 authorization keys on the client side, I used my server-side scripts to generate a pre-signed URL and send it back to the client, for example:

 const AWS = require('aws-sdk') const s3 = new AWS.S3() AWS.config.update({accessKeyId: 'your access key', secretAccessKey: 'you secret key'}) const myBucket = 'bucket-name' const myKey = 'path/to/your/key/file.extension' const signedUrlExpireSeconds = 60 * 5 // your expiry time in seconds. const url = s3.getSignedUrl('getObject', { Bucket: myBucket, Key: myKey, Expires: signedUrlExpireSeconds }) // return the url to client 

Use this URL in the interface to start the download:

 function download(url){ $('<iframe>', { id:'idown', src:url }).hide().appendTo('body').click(); } $("#downloadButton").click(function(){ $.ajax({ url: 'example.com/your_end_point', success: function(url){ download(url); } }) }); 
+8
source share

Other answers work here, but I would like to talk more about what works for me.

In my case, I was dealing with files too large for

 function download(url){ $('<iframe>', { id:'idown', src:url }).hide().appendTo('body').click(); } 

work. (Got url is too long ) My solution was to enable the hidden anchor tag and trigger a click on that tag if ajax succeeded. You cannot use the anchor tag immediately unless you care about errors.

S3 will respond with an XML error file if something goes wrong, so the browser will automatically display this XML response. By first trying to hit the URL with ajax, you can detect this error without showing ugly XML. Success in this ajax call is when you know that you can try downloading the file.

0
source share

All Articles