How I Upload Images in my Projects
An overview of how I upload images to S3 for my projects
I’ve uploaded a few images in the past for my projects and have found what I believe to be an ideal way to handle image uploads.
A bit of background before we get into the details. Many of my projects are serverless in nature, and I generally upload to S3. The following will describe how I handle images in my app with S3.
Let’s get started!
Since many of my projects are serverless based, images can be a hassle due to timeout, memory, and payload size limitations of the serverless functions.
This lead me to explore uploading images via S3 pre-signed URLs. These pre-signed URLs allow the system to upload images (objects) to S3 directly without AWS credentials or IAM permissions.
Below breaks down the steps needed to upload images to S3 using pre-signed URLs.
First we send a request to the server which would contain information about the image I am looking to upload. Not only am I using the image info to generate the URL, I am also storing the object key used to identify the image in S3 in my own DB.
Using the information about the image I generate the pre-signed URL and storing the object key used to identify the image in S3 in my own DB. I use the first-party SDKs from AWS to generate the pre-signed URL. There are a bunch of docs and articles on how to do this.
Returning the signed URL and any other information needed to upload the image to S3.
Upload the image via the pre-signed URL
Once an image is loaded into S3 there are various ways to serve these images. You can have the S3 bucket be public and use the images S3 url directly. I generally don’t recommend this approach unless you are working on a small project. My recommended way of serving images is using S3 + CloudFront. This allows you to keep your bucket private, add custom domains, and caching amongst many other benefits.
Hope you found this overview useful. Let me know on X if you want me to create a more in depth tutorial on handling images with S3 for your projects.
See more at: dpklabs.com
Happy Coding!