Duplicated images on upload
Hello,
I am using cloudinary with node and multer I successfully managed to store images but i noticed each time i upload an image it creates two copies : one with the public_id as a name (in the assets) and the other with the original name(in 'profiles' folder).
I want to delete both whenever i upload a new image but it only deletes the one in the assets and don't delete the one in the 'profiles' folder.
Can anyone please help ?
My Upload routes looks like this
import path from "path";
import express from "express";
import dotenv from "dotenv";
import cloudinary from "cloudinary";
import { CloudinaryStorage } from "multer-storage-cloudinary";
import multer from "multer";
dotenv.config();
const cloud = cloudinary.v2;
const router = express.Router();
cloud.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const storage = new CloudinaryStorage({
cloudinary: cloud,
params: {
folder: "profiles",
transformation: { gravity: "center", height: 300, width: 300, crop: "fill" },
public_id: (req, file) =>
`${file.originalname.split(".")[0]}-${Date.now()}`,
},
});
function checkFileType(file, cb) {
const filetypes = /jpg|jpeg|png/;
const extname = filetypes.test(
path.extname(file.originalname).toLocaleLowerCase()
);
const mimetype = filetypes.test(file.mimetype);
if (extname && mimetype) {
return cb(null, true);
} else {
cb(null, false);
}
}
const upload = multer({
storage,
fileFilter: function (req, file, cb) {
checkFileType(file, cb);
},
});
router.post("/", upload.single("image"), async (req, res) => {
try {
const result = await cloud.uploader.upload(req.file.path)
res.send(result);
} catch(error) {
console.log(error)
}
});
export default router;
router.post('/:id', async (req, res) =>{
try {
await cloud.uploader.destroy(req.params.id);
res.send(result);
} catch (err) {
return res.status(500).json({msg: err.message})
}
})
-
Hi Aboubacar,
Cloudinary supports only one upload with a single call to the Upload API and I see only one post in the code.
Can you please share the public_id of one of the resources in concern and I will check the logs for further details.
If you would like to delete multiple images then you can do so by passing their unique public_id's and invoking the destroy API for every one of them or alternatively you can also use the delete API which supports bulk deletion. Since the two uploaded files have different public_id's (public_id also includes folder name if the resource is inside the folder) you will have to invoke the destroy API twice with the unique names to delete both the files.
Regards,
Aditi
0
Post is closed for comments.
Comments
1 comment