This is an example project showing how to upload and download files and images using AWS Amplify, AWS AppSync, and Amazon S3
This project goes along with the GraphQL Tutorial - How to Manage Image & File Uploads & Downloads with AWS AppSync & AWS Amplify on Dev.to.
How do I upload images and files using GraphQL with AWS AppSync?
There are a few parts to this solution:
- You must first upload the image to a storage solution (in this example, Amazon S3)
- After you have finished uploading the image, you will need to store a reference to this image in a database using a GraphQL mutation.
- When you want to view a public image (public bucket), you need to:
- Query the image URL from your database using GraphQL
- When you want to view a private image (non-public bucket), you need to do two things:
- First, query the image reference from your database using GraphQL
- Get a signed URL for the image from S3
In this example, I show how to:
- Store images using GraphQL, AppSync, and S3 (both using public and private access)
- Fetch a list of images and render them in a React application
- Fetch a single image and render it in a React application
- Clone the project and change into the directory
git clone https://github.com/dabit3/react-amplify-appsync-files-s3.git
cd react-amplify-appsync-s3
- Install the dependencies
npm install
# or
yarn
- Initialize and deploy the amplify project
amplify init
amplify push
- Run the app
npm start
- Change the bucket policy in your S3 bucket for files in the
images
folder to be public (in order for the Product images to be publicly viewable):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::<YOUR_BUCKET_NAME>/public/images/*"
}
]
}
- Render either the private (Users) or public (Products) example in src/App.js:
import React from 'react'
import Products from './Products'
import Users from './Users'
function App() {
return (
<Users />
// or <Products />
)
}
export default App;
Click the button to deploy this application to the Amplify console.
Then change the bucket policy in your S3 bucket for files in the images
folder to be public (in order for the Product images to be publicly viewable):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::<YOUR_BUCKET_NAME>/public/images/*"
}
]
}