Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloudinary\Error: Missing required parameter - file - Express and Postman

first time trying to upload images to Cloudinary and I have come across an issue when using Express via Postman.

Using form-data on setting 'file' to upload an image to Cloudinary

As of now, when I try to access the req.body I get an empty object, so I guess that has to do with why cloudinary.uploader.upload cannot read the file passed as its first param, since its req.body.file, as shown in the code below.

cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_KEY,
    api_secret:  process.env.CLOUDINARY_SECRET
})



exports.upload = async (req, res) => {

  try{
   
console.log(req.body);
const result =  await cloudinary.uploader.upload(req.body.file, {
    public_id: `${Date.now()}`, 
    resource_type: "auto"
})

return res.json({
    public_id: result.public_id,
    url: result.secure_url
})

}catch(err){
  console.log(err)
}

} 

The error message I get:

{
  message: 'Missing required parameter - file',
  name: 'Error',
  http_code: 400
}

Any suggestions to solve this issue?

like image 265
Zakaria Bougroug Avatar asked May 23 '26 01:05

Zakaria Bougroug


2 Answers

I solved it! I was not able to pass the form-data as req.body to the server, so I had to try and access it through req.files, but was not able to with that either, so I searched a bit and found a middleware 'express-fileupload', and that did the trick. I just added it in my app.js and used

const fileupload = require('express-fileupload'); 

app.use(fileupload({useTempFiles: true}))

So now I can access my req.files.

exports.upload = async (req, res) => {

  const file = req.files.image

  try{
console.log(file);

const result =  await cloudinary.uploader.upload(file.tempFilePath, {
    public_id: `${Date.now()}`, 
    resource_type: "auto"
})

res.json({
    public_id: result.public_id,
    url: result.secure_url
})

}catch(err){
  console.log("Error", err)
return res.status(400).json({error: err})
}

} 

The response I get is:

{
  name: 'some-image.png',
  data: <Buffer >,
  size: 99770,
  encoding: '7bit',
  tempFilePath: ' **C:\\filepath\some-image.png** ',
  truncated: false,
  mimetype: 'image/png',
  md5: 'b5f612a571442bf604952fd12c47c1bf',
  mv: [Function: mv]
}
POST /cloudinary/upload-images 200 1617.944 ms - 119

And it is uploaded successfully to my Cloudinary.

like image 163
Zakaria Bougroug Avatar answered May 24 '26 15:05

Zakaria Bougroug


const result = await cloudinary.uploader.upload(req.file, { public_id: ${Date.now()}, resource_type: "auto" })

and add file from form data and type should be File

enter image description here

like image 27
Kenil Barvaliya Avatar answered May 24 '26 13:05

Kenil Barvaliya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!