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' picture.
My upload route 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;
And the delete route
import express from "express";
import dotenv from "dotenv";
import cloudinary from "cloudinary";
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,
});
router.post('/:id', async (req, res) =>{
try {
await cloud.uploader.destroy(req.params.id);
// await cloud.uploader.destroy(`/profiles/${req.params.id}`);
res.send(result);
} catch (err) {
return res.status(500).json({msg: err.message})
}
})
export default router;
Can anyone help ?
In case anyone face the same issue I was sending the image twice in the upload route Just change it to this
router.post("/", upload.single("image"), async (req, res) => {
try {
res.json(req.file);
} catch (error) {
console.log(error);
}
});