📝
Amplify で S3 からファイルをダウンロードするアプリを作ってみた
Download files - React Native - AWS Amplify Gen 1 Documentation
上記ドキュメントの内容を試してみました。
前提
- Amplify CLI の実行環境: Cloud9
- Amplify CLI のバージョン: 13.0.1
- JavaScript ライブラリ: React
- Amplify CLI で使用する認証情報: IAM ユーザーの認証情報
01. プロジェクトの準備
$ mkdir amplify-s3-download-app
$ cd amplify-s3-download-app
$ npx create-react-app my-app
$ cd my-app
$ mkdir -p ~/.npm-global
$ npm config set prefix '~/.npm-global'
$ echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
$ source ~/.bashrc
$ npm install -g @aws-amplify/cli
02. Amplify プロジェクトの初期化
$ amplify init
$ amplify add storage
Content (Images, audio, video, etc.)
You need to add auth (Amazon Cognito) to your project in order to add storage for user files. Do you want to add auth now? (Y/n) ‣ Y
Default configuration
Username
No, I am done.
Who should have access: … (Use arrow keys or type to filter)
❯ Auth and guest users
? What kind of access do you want for Guest users? … (Use arrow keys or type to filter)
● create/update
● read
● delete
$ amplify push
03. S3 バケットにファイルをアップロード
手順 02 で作成された S3 バケットに public というフォルダを作成します。
public フォルダに zip ファイルをアップロードします。
04. React アプリにダウンロード機能を追加
$ npm install aws-amplify @aws-amplify/ui-react
src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Amplify } from 'aws-amplify';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
src/App.js
import React from 'react';
import { getUrl } from 'aws-amplify/storage';
function App() {
const downloadFile = async () => {
try {
const { url } = await getUrl({
key: 'test.zip', // S3 の public フォルダにあるファイル名
options: { accessLevel: 'public' },
});
window.open(url, '_blank');
} catch (err) {
console.error('Download error:', err);
}
};
return (
<div style={{ padding: 20 }}>
<h1>S3 File Download App</h1>
<button onClick={downloadFile}>Download File</button>
</div>
);
}
export default App;
05. デプロイ
$ amplify add hosting
Amazon CloudFront and S3
$ amplify publish
Your app is published successfully.
https://d2eukhof8voszk.cloudfront.net
06. 動作確認
手順 05 の CloudFront の URL にアクセスします。
ボタンをクリックしてファイルをダウンロードできれば OK です。
まとめ
今回は Amplify で S3 からファイルをダウンロードするアプリを作ってみました。
どなたかの参考になれば幸いです。
Discussion