Casper
Casper

Reputation: 1723

How to download S3 object data using plain Javascript (no Node)

So I am using AWS Javascript SDK to S3 object, using this method:

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getObject-property

The call completed successfully, however it only shows the Object data with string.

How can I download this file from browser with only plain Javascript?

Upvotes: 0

Views: 2061

Answers (2)

Roizy Kish
Roizy Kish

Reputation: 61

Here is how you can download a file from AWS using vanilla JavaScript.

let bucket_name = 'name of your bucket';
let folder_name = 'name of your folder';
let file_name = 'name of your file';
fetch('https://' + bucket_name + '.s3.amazonaws.com/' + folder_name + '/' + file_name + '.jpg')
.then(resp => resp.blob())
.then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = file_name.split("/").pop();
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    alert('your file has downloaded!');
})
.catch(() => console.log('oh no!'));

Upvotes: 0

Chase
Chase

Reputation: 3105

The documentation clearly states in the Callback section of the getObject method that data.Body will return a "Buffer, Typed Array, Blob, String, ReadableStream".

That's your file.

Upvotes: 3

Related Questions