DoneDeal0
DoneDeal0

Reputation: 6257

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: enter image description here

Here 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);
  }
});

Upvotes: 1

Views: 6987

Answers (2)

Aryan
Aryan

Reputation: 3636

You have to add just this code in your api

            let resultHandler = function (err) {
                if (err) {
                    console.log("unlink failed", err);
                } else {
                    console.log("file deleted");
                }
            }

            fs.unlink(req.file.path, resultHandler);

Upvotes: 2

Deepak Poojari
Deepak Poojari

Reputation: 766

The best way to optimise this is not to store data in local and then upload, just upload the buffer data that you get in API. most of the cloud storage providers has that, also cloudinary has stream upload.

https://support.cloudinary.com/hc/en-us/community/posts/360007581379-Correct-way-of-uploading-from-buffer-

Regarding your code, the code LGTM. Problem might be some exception thrown by your code and the code fs.unlinkSync(file.path) is never reached.

Upvotes: 1

Related Questions