Saturday 26 September 2020

How to delete files uploaded with multer once they are stored in the cloud?

I upload files to an Express server with multer. They are parsed and stored to Cloudinary. So far so good. However, all the files are stored in an upload folder on my server, and take a lot of space while I don't need them. How to remove these files once an upload to cloudinary is completed?Here is a screenshot of the upload folder:​upload folder created/updated by MulterHere is the code:const express = require("express"); const router = express.Router(); const cloudinary = require("cloudinary").v2; const multer = require("multer"); const fs = require("fs"); // multer config const dest = "uploads/"; const limits = { fileSize: 1000 * 1000 * 4 }; // limit to 4mb const upload = multer({ dest, limits }); // upload image router.post("/upload-images", upload.array("image"), (req, res) => { const { images } = req.files; const { userId } = req.body; try { if (images) { images.forEach(file => { cloudinary.uploader.upload( file.path, { resource_type: "image", public_id: `myapp/users/${userId}/${file.originalname}` }, (err, res) => { if (err) { return fs.unlinkSync(file.path); } fs.unlinkSync(file.path); return res.secure_url } ); }); } } catch (err) { return res.json(err); } }); Thanks!

Submitted September 26, 2020 at 04:09PM by MonsieurLeland

No comments:

Post a Comment