ファイルのダウンロード
以前アップロードしたデータを取得するために、以下のオプションが利用可能です:
ダウンロードURLの生成
保存されたファイルの署名付きURLと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は結果のurlプロパティに署名付きURLを返します。これを使用してユーザーがクリックするダウンロードリンクを作成できます。expiresAtプロパティは、URLが有効期限切れになる時刻を表すDateオブジェクトです。
テンプレートまたはJSXコード内で、urlプロパティを使用してファイルへのリンクを作成できます:
<a href="{signedURL.url.toString()}" target="_blank" rel="noreferrer"> {fileName} </a>ファイルの存在確認
ストレージカテゴリのgetUrl APIのvalidateObjectExistenceオプションを使用して、ファイルの存在を確認できます。このフラグが有効な場合、getUrl呼び出しはファイルが存在すれば署名付きURLを返し、存在しない場合は404エラーを発生させます。これにより、署名付きURLを生成する際にオブジェクトが存在するかどうかを確認でき、その後それを使用してオブジェクトをダウンロードできます。
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の有効期限
expiresInオプションを使用してURLの利用可能性を制限できます。この設定は60秒で有効期限が切れる署名付きURLを返します:
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
ファイルをメモリ内バッファにダウンロードします。
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;ダウンロードされたファイルのテキスト値を取得する
ファイルの値をblob、json、またはtextの3つの形式のいずれかで使用できます。bodyプロパティで対応するメソッドを呼び出して、設定されたデータを対応する形式で使用できます。
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);}ダウンロードタスクの進行状況を追跡する
ダウンロードの進行状況を追跡するには、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;ダウンロードタスクをキャンセルする
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. }}よくある質問
ユーザーは予期しない問題に遭遇する可能性があるため、ドキュメントに事前に通知とオープンイシューへのリンクを記載しています。必要なものに投票して、チームの優先順位付けを支援してください。
- 画像圧縮またはS3バケットのCloudFront CDNキャッシングはまだ利用できません。
- 現在、他のユーザーのidentityIdを取得するAPIがありません。
downloadDataを呼び出す前に、他の場所からこれを取得する必要があります。 downloadDataはキャッシュ制御オプションを提供せず、実行時HTTPキャッシング動作に依存しています。キャッシュをバイパスする必要がある場合は、getUrlAPIを使用してファイルをダウンロードするための署名付きURLを作成できます。downloadDataはS3オブジェクトのバージョン管理をサポートしておらず、常に最新バージョンをダウンロードします。- CognitoグループベースのファイルアクセスのAPIはありません。これを実現するためにAmplify Gen2 Storageを使用できます。