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.
import { getUrl } from 'aws-amplify/storage';
const getUrlResult = await getUrl({ path: 'public/album/2024/1.jpg', // Alternatively, path: ({identityId}) => `protected/${identityId}/album/2024/1.jpg` options: { validateObjectExistence?: false, // Check if object exists before creating a URL expiresIn?: 20 // validity of the URL, in seconds. defaults to 900 (15 minutes) and maxes at 3600 (1 hour) useAccelerateEndpoint?: true; // Whether to use accelerate endpoint },});console.log('signed URL: ', getUrlResult.url);console.log('URL expires at: ', getUrlResult.expiresAt);
import { getUrl } from 'aws-amplify/storage';
const getUrlResult = await getUrl({ key: 'album/2024/1.jpg', options: { accessLevel?: 'protected' , // can be 'private', 'protected', or 'guest' but defaults to `guest` targetIdentityId?: 'XXXXXXX', // id of another user, if `accessLevel` is `protected` validateObjectExistence?: false, // Check if object exists before creating a URL expiresIn?: 20 // validity of the URL, in seconds. defaults to 900 (15 minutes) and maxes at 3600 (1 hour) useAccelerateEndpoint?: true; // Whether to use accelerate endpoint },});console.log('signed URL: ', getUrlResult.url);console.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:
<a href="{signedURL.url.toString()}" target="_blank" rel="noreferrer"> {fileName} </a>
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.
import { getUrl } from 'aws-amplify/storage';
// To check for existence of a fileawait getUrl({ path: 'public/album/2024/1.jpg', // Alternatively, path: ({identityId}) => `protected/${identityId}/album/2024/1.jpg` options: { validateObjectExistence: true // defaults to false }});
import { getUrl } from 'aws-amplify/storage';
// To check for existence of a fileawait getUrl({ key: 'album/2024/1.jpg', options: { validateObjectExistence: true // defaults to false }});
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:
import { getUrl } from 'aws-amplify/storage';
await getUrl({ path: 'public/album/2024/1.jpg', // Alternatively, path: ({identityId}) => `protected/${identityId}/album/2024/1.jpg` options: { expiresIn: 60 } });
import { getUrl } from 'aws-amplify/storage';
await getUrl({ key: 'album/2024/1.jpg', options: { expiresIn: 60 } });
downloadData
Download a file to in-memory buffer.
import { downloadData } from 'aws-amplify/storage';
// Downloads file content to memoryconst { body, eTag } = await downloadData({ path: 'public/album/2024/1.jpg', // Alternatively, path: ({identityId}) => `protected/${identityId}/album/2024/1.jpg` options: { onProgress: (event) => { console.log(event.transferredBytes); } // optional progress callback bytesRange: { start: 1024, end: 2048 } // optional bytes range parameter to download a part of the file, the 2nd MB of the file in this example }}).result;
import { downloadData } from 'aws-amplify/storage';
// Downloads file content to memoryconst { body, eTag } = await downloadData({ key: 'album/2024/1.jpg', options: { accessLevel: 'guest', // access level of the file being downloaded targetIdentityId: 'xxxxxxx', // the identity id of another user, required when setting accessLevel to 'protected' onProgress: (event) => { console.log(event.transferredBytes); } // optional progress callback bytesRange: { start: 1024, end: 2048 } // optional bytes range parameter to download a part of the file, the 2nd MB of the file in this example }}).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.
import { downloadData } from 'aws-amplify/storage';
try { const downloadResult = await downloadData({ path: 'public/album/2024/1.jpg', // Alternatively, path: ({identityId}) => `protected/${identityId}/album/2024/1.jpg` }).result; const text = await downloadResult.body.text(); // Alternatively, you can use `downloadResult.body.blob()` // or `downloadResult.body.json()` get read body in Blob or JSON format. console.log('Succeed: ', text);} catch (error) { console.log('Error : ', error);}
import { downloadData } from 'aws-amplify/storage';
try { const downloadResult = await downloadData({ key: 'album/2024/1.jpg' }).result; const text = await downloadResult.body.text(); // Alternatively, you can use `downloadResult.body.blob()` // or `downloadResult.body.json()` get read body in Blob or JSON format. console.log('Succeed: ', text);} catch (error) { console.log('Error : ', error);}
Track the progress of a download task
To track the progress of your download, you can use onProgress
:
import { downloadData } from 'aws-amplify/storage';
// Download a file from s3 bucketconst { body, eTag } = await downloadData( { path: 'public/album/2024/1.jpg', // Alternatively, path: ({identityId}) => `protected/${identityId}/album/2024/1.jpg` options: { onProgress: (progress) { console.log(`Download progress: ${(progress.transferredBytes/progress.totalBytes) * 100}%`); } } }).result;
import { downloadData } from 'aws-amplify/storage';
// Download a file from s3 bucketconst { body, eTag } = await downloadData( { key: 'album/2024/1.jpg', options: { onProgress: (progress) { console.log(`Download progress: ${(progress.transferredBytes/progress.totalBytes) * 100}%`); } } }).result;
Cancel a download task
import { downloadData, isCancelError } from 'aws-amplify/storage';
const downloadTask = downloadData({ path: 'public/album/2024/1.jpg', // Alternatively, path: ({identityId}) => `protected/${identityId}/album/2024/1.jpg` });downloadTask.cancel();try { await downloadTask.result;} catch (error) { if (isCancelError(error)) { // Handle error thrown by task cancellation. }}
import { downloadData, isCancelError } from 'aws-amplify/storage';const downloadTask = downloadData({ key: 'album/2024/1.jpg' });downloadTask.cancel();try { await downloadTask.result;} catch (error) { if (isCancelError(error)) { // Handle error thrown by task cancellation. }}
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.
downloadData
is cached; if you have recently modified a file you may not get the latest version right away. You can pass incacheControl: 'no-cache'
to get the latest version.downloadData
only returns the latest cached version of the file; there is not yet an API to view prior versions.- Image compression or CloudFront CDN caching for your S3 buckets is not yet possible.
- There is no API for Cognito Group-based access to files.
- There is currently no API for getting the identityId of other users; you have to retrieve this from elsewhere before calling
Storage.get
.