Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete an Image from Amazon S3 (Next.js, Mongodb, Mongoose)

I am trying to add a deleteImage function from my current front end that communicates with my backend via api routes. Here is a function i am using for uploading images:

const uploadImages = async (ev) => {
    const files = ev.target?.files;
    if (files?.length > 0) {
      setIsUploading(true);
      const data = new FormData();
      for (const file of files) {
        data.append("file", file);
      }
      const res = await axios.post("/api/upload", data);
      setImages((oldImages) => {
        return [...oldImages, ...res.data.links];
      });
      setIsUploading(false);
    }
  };

and here is the upload.js api route that the "uploadImages" function is communicating with:

import multiparty from "multiparty";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import fs from "fs";
import mime from "mime-types";

const bucketName = "ecommerce";

export default async function handle(req, res) {
  const form = new multiparty.Form();
  const { fields, files } = await new Promise((resolve, rejecct) => {
    form.parse(req, (err, fields, files) => {
      if (err) rejecct(err);
      resolve({ fields, files });
    });
  });
  console.log("length", files.file.length);
  const client = new S3Client({
    region: "us-west-1",
    credentials: {
      accessKeyId: process.env.S3_ACCESS_KEY,
      secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
    },
  });
  const links = [];
  for (const file of files.file) {
    const ext = file.originalFilename.split(".").pop();
    const newFilename = Date.now() + "." + ext;
    await client.send(
      new PutObjectCommand({
        Bucket: bucketName,
        Key: newFilename,
        Body: fs.readFileSync(file.path),
        ACL: "public-read",
        ContentType: mime.lookup(file.path),
      })
    );
    const link = `https://${bucketName}.s3.amazonaws.com/${newFilename}`;
    links.push(link);
  }

  return res.json({ links });
}

export const config = {
  api: { bodyParser: false },
};

how would i create a similar function to remove the images from my amazon s3 bucket? I imagine that I also would need to create a "delete.js" api path as well? or maybe not?

Thanks Coders.

i tried a this, but it only removes the image from the front end. I need it removed from the backend as well:

const deleteImage = (index) => {
    const updatedImages = [...images];
    updatedImages.splice(index, 1);
    setImages(updatedImages);
  };
like image 422
Chris Ware Codes Avatar asked Dec 11 '25 11:12

Chris Ware Codes


1 Answers

use this in your API to remove files from s3 and here the key is your file name and Bucket is your s3bucket name.

const params ={
    Bucket:process.env.AWS_BUCKET_NAME,
    Key:req.params.imageName
}
try {
    const data = await s3.send(new DeleteObjectCommand(params));
    return res.status(200).json({ success: data, status: true });
    // console.log("Success. Object deleted.", data);
    // return data; // For unit tests.
  } catch (err) {
    return res.status(404).json({ error: err, status: false  });
  }
like image 160
Rajesh Senapati Avatar answered Dec 13 '25 05:12

Rajesh Senapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!