Search code examples
node.jsfile-uploadcloudinary

How to upload a file to a certain folder in Cloudinary? Node JS


In cloudinary I have a folder called images, I want to upload the files into that folder. I have done set up the cloudinary config. The storage options and the file filter has been done. In the request, I send the post request that will upload the file to cloudinary, but not to the folder. How can I upload a file to a certain folder in Cloudinary?

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, './images/');
  },
  filename: (req, file, cb) => {
    cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  if (!file.mimetype.match(/jpe|jpeg|png|gif$i/)) {
    cb(new Error('File is not supported'), false);
    return;
  }

  cb(null, true);
};

const upload = multer({
  storage,
  fileFilter
});

router.post('/',  upload.single('profileImage'), async (req,res) => {
  const result = await cloudinary.v2.uploader.upload(req.file.path);
})

Solution

  • When you're performing the upload request you can specify a set of options to be used for that upload. In these options, you can specify the 'public_id' (filename) and/or 'folder' of where the file should be stored.

    For example, to upload a file to a folder called 'test', you can use the code below:

    cloudinary.v2.uploader.upload(
        "path/to/file",
        {
            folder: "test",
        },
        function(error, result) {
            console.log(error,result);
        }
    );
    

    You can find out all available options for the upload method via this section of the documentation: https://cloudinary.com/documentation/image_upload_api_reference#upload_method