Javascript to Download a File from Amazon S3 Bucket

Javascript to download a file from amazon s3 bucket?

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
}
}
);

AWS S3 File Download from the client-side

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));

Can you download a file from Amazon S3 bucket without having AWS login credentials

There are three common ways of accessing S3 objects/files without the need for AWS credentials:

  1. Granting public access to the bucket, a folder in the bucket or individual objects. This is probably the easiest to setup and use, but your objects are, well, public.

  2. Use S3 pre-signed url url. These are temporary urls that your backend would have to generate for the front-end to use. The urls can be for downloading or uploading files. Anyone with these urls can download/upload files to your bucket, but since urls are temporary, hot-linking the urls is limited.

  3. Front your bucket with CloudFront. This allows to keep your bucket fully private, and all your files will be accessed through CloudFront edge locations, which can also speedup your website.

How do you download a file from AWS S3 to a client's device?

S3 supports the ability to generate a pre-signed URL via the AWS Javascript API. Users can then GET this URL to download the S3 object to their local device.

See this question for a Node.js code sample.

How to download file from AWS S3 using getObject in Reactjs?

For anyone else who may want to do this in future directly from the client side, I was able to implement this by using Blob to convert the data into a Blob URL and then running the function when Download is clicked.

My InputDownload file from above now looks like this:

import React, { useState } from 'react';
import { ListGroup, Dropdown } from 'react-bootstrap';
import AWS from 'aws-sdk';

const InputDownload = () => {
const [template, setTemplate] = useState('Choose Template');

AWS.config.update({
accessKeyId: process.env.REACT_APP_ACCESS_ID,
secretAccessKey: process.env.REACT_APP_ACCESS_KEY,
});

const handleClick = (e) => {
e.preventDefault();
};

const handleDownload = () => {
const s3 = new AWS.S3();

const params = {
Bucket: process.env.REACT_APP_INTERNAL_BUCKET_NAME,
Key: `templates/${template}`,
};


function downloadBlob(blob, name = `${template}.csv`) {
// Convert your blob into a Blob URL (a special url that points to an object in the browser's memory)
const blobUrl = URL.createObjectURL(blob);
// Create a link element
const link = document.createElement('a');
// Set link's href to point to the Blob URL
link.href = blobUrl;
link.download = name;
// Append link to the body
document.body.appendChild(link);
// Dispatch click event on the link
// This is necessary as link.click() does not work on the latest firefox
link.dispatchEvent(
new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window,
})
);

// Remove link from body
document.body.removeChild(link);
}

s3.getObject(params, (err, data) => {
if (err) {
console.log(err, err.stack);
} else {
let csvBlob = new Blob([data.Body.toString()], {
type: 'text/csv;charset=utf-8;',
});
downloadBlob(csvBlob, `${template}`);
}
});

}

return (
<>
<form className='bg-white my-4' onSubmit={handleClick}>
<Dropdown>
<Dropdown.Toggle variant='secondary' id='dropdown-basic'>
{template}
</Dropdown.Toggle>

<Dropdown.Menu>
<Dropdown.Item onSelect={() => setTemplate('T1')}>
T1</Dropdown.Item>
<Dropdown.Item onSelect={() => setTemplate('IV1')}>
IV1
</Dropdown.Item>
<Dropdown.Item onSelect={() => setTemplate('IV2')}>
IV2
</Dropdown.Item>
<Dropdown.Item onSelect={() => setTemplate('DV1')}>
DV1
</Dropdown.Item>

</Dropdown.Menu>
</Dropdown>
<input
type='submit'
value='Download'
className='btn btn-primary btn-block mt-3'
onClick={handleDownload}
/>

</form>
</>
);
};

export default InputDownload;

nodejs: how to download a zip file from AWS S3 bucket, save as local file in EC2 instance and unzip it?

Create a read stream for the object and a write stream for the local file and pipe the read stream to the write stream, something like this:

const AWS = require('aws-sdk');
const path = require('path');
const fs = require('fs');

const s3 = new AWS.S3();

const params = {
Bucket: 'mybucket',
Key: 'cats/siberian.png'
};

const rs = s3.getObject(params).createReadStream();
const ws = fs.createWriteStream(path.join('myfolder', 'siberian.png'));

rs.pipe(ws);


Related Topics



Leave a reply



Submit