Download files
Storage Image React UI Component
You can easily display images in your app by using the cloud-connected Storage Image React UI component. This component fetches images securely from your storage resource and displays it on the web page.
npm add @aws-amplify/ui-react-storage aws-amplify
import { StorageImage } from '@aws-amplify/ui-react-storage';
export const DefaultStorageImageExample = () => { return <StorageImage alt="cat" path="your-path/cat.jpg" />;};
Learn more about how you can further customize the UI component by referring to the Storage Image documentation.
To further customize your in-app experience, you can use the getUrl
or downloadData
API from the Amplify Library for Storage.
Get or download file from a URL
With the getUrl
API, you can get a presigned URL which is valid for 900 seconds or 15 minutes by default. You can use this URL 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.
import { getUrl } from 'aws-amplify/storage';
const linkToStorageFile = await getUrl({ path: "album/2024/1.jpg", // Alternatively, path: ({identityId}) => `album/{identityId}/1.jpg` options: { validateObjectExistence?: false, // defaults to false 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: ', linkToStorageFile.url);console.log('URL expires at: ', linkToStorageFile.expiresAt);
Inside your template or JSX code, you can use the url
property to create a link to the file:
<a href={linkToStorageFile.url.toString()} target="_blank" rel="noreferrer"> {fileName} </a>
More getUrl
options
Option | Type | Description |
---|---|---|
useAccelerateEndpoint | boolean | Whether to use accelerate endpoint. Read more at Transfer Acceleration |
validateObjectExistence | boolean | Whether to head object to make sure the object existence before downloading. Defaults to false |
expiresIn | number | Number of seconds till the URL expires. The expiration time of the presigned url is dependent on the session and will max out at 1 hour. |
Download to a file
Use the downloadData
API to download the file locally.
import { downloadData } from 'aws-amplify/storage';
// Downloads file content to memoryconst { body, eTag } = await downloadData({ path: "/album/2024/1.jpg", options: { // optional progress callback onProgress: (event) => { console.log(event.transferredBytes); } // optional bytes range parameter to download a part of the file, the 2nd MB of the file in this example bytesRange: { start: 1024, end: 2048 } }}).result;
Get the text value of downloaded File
You can get 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: "/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);}
Monitor download progress
import { downloadData } from 'aws-amplify/storage';
// Download a file from S3 bucketconst { body, eTag } = await downloadData( { path: "/album/2024/1.jpg", options: { onProgress: (progress) { console.log(`Download progress: ${(progress.transferredBytes/progress.totalBytes) * 100}%`); } } }).result;
Cancel download
import { downloadData, isCancelError } from 'aws-amplify/storage';
const downloadTask = downloadData({ path: "/album/2024/1.jpg" });downloadTask.cancel();try { await downloadTask.result;} catch (error) { if (isCancelError(error)) { // Handle error thrown by task cancellation. }}
More download options
Option | Type | Description | Reference Links |
---|---|---|---|
useAccelerateEndpoint | boolean | Whether to use accelerate endpoint. | Transfer Acceleration |
bytesRange | { start: number; end:number; } | bytes range parameter to download a part of the file. | |
onProgress | callback | Callback function tracking the upload/download progress. |
Frequently Asked Questions
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 callingStorage.get
.