Page updated Jan 16, 2024

Download files

The following options are available for retrieving previously uploaded data:

Generate a download URL

Get a presigned URL of a stored file and expiration of URL. You can specify access level of file

1import { getUrl } from 'aws-amplify/storage';
2
3const getUrlResult = await getUrl({
4 key: filename,
5 options: {
6 accessLevel?: 'guest' , // can be 'private', 'protected', or 'guest' but defaults to `guest`
7 targetIdentityId?: 'XXXXXXX', // id of another user, if `accessLevel` is `guest`
8 validateObjectExistence?: false, // defaults to false
9 expiresIn?: 20 // validity of the URL, in seconds. defaults to 900 (15 minutes) and maxes at 3600 (1 hour)
10 useAccelerateEndpoint?: true; // Whether to use accelerate endpoint.
11 },
12});
13console.log('signed URL: ', getUrlResult.url);
14console.log('URL expires at: ', getUrlResult.expiresAt);

getUrl returns a signed URL in the url property of the result. You can use this to create a download link for users to click on. The expiresAt property is a Date object that represents the time at which the URL will expire.

Inside your template or JSX code, you can use the url property to create a link to the file:

1<a href="{signedURL.url.toString()}" target="_blank" rel="noreferrer">
2 {fileName} </a
3>;

This function does not check if the file exists by default. As result, the signed URL may fail if the file to be download does not exist.

Check for existence of a file

You can check for the existence of a file in the storage category's getUrl API using the validateObjectExistence option. When this flag is enabled a getUrl call will return a pre-signed URL if the file exists and raise a 404 error if it does not. This allows you to check if an object exists during generating the presigned URL, which you can then use to download that object.

1import { getUrl } from 'aws-amplify/storage';
2
3// To check for existence of a file
4await getUrl({
5 key: filename,
6 options: {
7 validateObjectExistence: true // defaults to false
8 }
9});

getUrl expiry

You can use expiresIn option to limit the availability of your URLs. This configuration returns the pre-signed URL that expires in 60 seconds:

1import { getUrl } from 'aws-amplify/storage';
2
3await getUrl({ key: 'filename.txt', options: { expiresIn: 60 } });

The expiration time of the presigned url is dependent on the session and will max out at 1 hour.

downloadData

Download a file to in-memory buffer.

1import { downloadData } from 'aws-amplify/storage';
2
3// Downloads file content to memory
4const { body, eTag } = await downloadData({
5 key,
6 data: file,
7 options: {
8 accessLevel: 'guest', // access level of the file being downloaded
9 targetIdentityId: 'xxxxxxx', // the identity id of another user, required when setting accessLevel to 'protected'
10 onProgress: (event) => {
11 console.log(event.transferredBytes);
12 } // optional progress callback
13 bytesRange: {
14 start: 1024,
15 end: 2048
16 } // optional bytes range parameter to download a part of the file, the 2nd MB of the file in this example
17 }
18}).result;

Get the text value of downloaded File

You can consume the value of file in any of the three formats: blob, json, or text. You can call the respective method on the body property to consume the set data in the respective format.

1import { downloadData } from 'aws-amplify/storage';
2
3try {
4 const downloadResult = await downloadData({ key: filename }).result;
5 const text = await downloadResult.body.text();
6 // Alternatively, you can use `downloadResult.body.blob()`
7 // or `downloadResult.body.json()` get read body in Blob or JSON format.
8 console.log('Succeed: ', text);
9} catch (error) {
10 console.log('Error : ', error);
11}

Track the progress of a download task

To track the progress of your download, you can use onProgress:

1import { downloadData } from 'aws-amplify/storage';
2
3// Download a file from s3 bucket
4const { body, eTag } = await downloadData(
5 {
6 key,
7 data: file,
8 options: {
9 onProgress: (progress) {
10 console.log(`Downloaded: ${progress.transferredBytes}/${progress.totalBytes}`);
11 }
12 }
13 }
14).result;

Cancel a download task

1import { downloadData, isCancelError } from 'aws-amplify/storage';
2
3const downloadTask = downloadData({ key, data: file });
4downloadTask.cancel();
5try {
6 await downloadTask.result;
7} catch (error) {
8 if (isCancelError(error)) {
9 // Handle error thrown by task cancellation.
10 }
11}

To get the metadata in result for all APIs you have to configure user defined metadata in CORS.

Learn more about how to setup an appropriate CORS Policy.

Frequently Asked Questions

Users can run into unexpected issues, so we are giving you advance notice in documentation with links to open issues - please vote for what you need, to help the team prioritize.