Image or File Upload with AWS S3
This boilerplate includes functionality to interact directly with AWS S3 for image or file uploads. Follow these steps to get started:
Getting Started
Step 1: Create an AWS Account and Bucket
First, create an AWS account and set up a new S3 bucket. Here is an example screenshot of how your S3 bucket setup might look:
Step 2: Add Your AWS Secrets to the .env
File
Add your AWS credentials and bucket information to your .env
file:
AWS_REGION=aws-region-eg-eu-west-2
AWS_ACCESS_KEY_ID=your-aws-access-key
AWS_SECRET_ACCESS_KEY=your-aws-secret-key
AWS_BUCKET_NAME=your-aws-bucket-name
Step 3: Generate an Upload URL
Use the following code to generate an upload URL and upload a file to your S3 bucket.
import { trpc } from "../utils/trpc"; // Adjust the import path as needed
import { getFileExtension } from "../utils/file"; // Utility to get file extension
const { mutateAsync: generateUploadUrl } =
trpc.image.generateUploadUrl.useMutation();
const handleUpload = async (selectedImage: File) => {
const { uploadUrl, fileName } = await generateUploadUrl({
fileExtension: getFileExtension(selectedImage.name),
});
await fetch(uploadUrl, {
method: "PUT",
body: selectedImage,
});
// fileName is the name of the file stored in your S3 bucket.
// You can use it to generate a public URL for the image
console.log(`File uploaded successfully: ${fileName}`);
};
// Example usage in a component
const MyComponent = () => {
const onFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files[0]) {
handleUpload(event.target.files[0]);
}
};
return <input type="file" onChange={onFileChange} />;
};
Summary
By following these steps, you can easily set up and manage file uploads to AWS S3 in your project. Create your AWS account and bucket, configure your environment variables, and use the provided code to handle file uploads securely and efficiently.