Notes:

Setting Up S3 Bucket

import { S3Client, ... } from "@aws-sdk/client-s3"

const s3 = new S3Client({
	credentials: {
		accessKeyId: accessKey, //accessKey is a dotEnv variable
		secretAccessKey: secretAccessKey, //secretAccesskey is a dotEnv variable
	},
	region: bucketRegion
});

Using Multer

Multer is middleware which handles file uploading. When using the single() function from the multer package, multer adds a file object to the req object which contains information about the uploaded file.

const storage = multer.memoryStorage()
const upload = multer({ storage: storage })
...
//routes, other code
router.post("/", upload.single('image'), async (req: any, res: any) => {
	...
}

Backend

We will need to modify our event routes to account for the addition of images into the S3 bucket

For example:

Frontend

In the frontend, one possible solution is to send only the image as a formData() so that the image is encoded as a “multipart/formdata” file and continue to send the other parameters as a json file. In the backend, we can add just the image data onto the S3 bucket and store the image link in the MongoDB

const [file, setFile] = useState<File>();
...
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        if (!file) {
          alert("Please select a file.");
          return;
        }
        // create FormData object
        const formData = new FormData();
        formData.append("image", file);
      
        try {
          // upload image to S3 bucket
          const response = await fetch(`${PORT}/upload"` {
            method: "POST",
            body: formData,
          });
      
          if (response.ok) {
            const data = await response.text();
            const imageURL = data; // get image url from S3 response
            await fetch(`${PORT}/posts/` {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                ...
              }),
            });
            alert("Successfully uploaded");
          } else {
            console.error("Failed to upload image");
          }
        } catch (error) {
          console.error(error);
        }
      };

Retrieving Image