Home > Enterprise >  trying to upload image to nodejs api but it returns with error
trying to upload image to nodejs api but it returns with error

Time:09-22

I am trying to upload image to my node.js server and when I upload nothing and just send the request to post without image, it works fine but whenever I try to post the image node.js shows error in console

here is the link to post "http://localhost:3001/databaseGym/logo" here is my code to handle post operation to that link

 Router.post('/logo', upload.single('file'), (req, res) => {
    console.log("working");
    //res.json({ file: req.file });
    res.send("done");
  });

and here is my code for upload in upload.single()

// Create storage engine
const storage = new GridFsStorage({
  url: url,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename = buf.toString('hex')   path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: 'logo'
        };
        resolve(fileInfo);
      });
    });
  }
});
const upload = multer({ storage });

and here is the screenshot of postman app through which I am sending image postman app image

and here is the error

MulterError: Unexpected field
    at wrappedFileFilter (D:\web dev\gym website\server_gym\node_modules\multer\index.js:40:19)
    at Busboy.<anonymous> (D:\web dev\gym website\server_gym\node_modules\multer\lib\make-middleware.js:114:7)
    at Busboy.emit (node:events:394:28)
    at Busboy.emit (D:\web dev\gym website\server_gym\node_modules\busboy\lib\main.js:38:33)
    at PartStream.<anonymous> (D:\web dev\gym website\server_gym\node_modules\busboy\lib\types\multipart.js:213:13)
    at PartStream.emit (node:events:394:28)
    at HeaderParser.<anonymous> (D:\web dev\gym website\server_gym\node_modules\dicer\lib\Dicer.js:51:16)
    at HeaderParser.emit (node:events:394:28)
    at HeaderParser._finish (D:\web dev\gym website\server_gym\node_modules\dicer\lib\HeaderParser.js:68:8)
    at SBMH.<anonymous> (D:\web dev\gym website\server_gym\node_modules\dicer\lib\HeaderParser.js:40:12)

CodePudding user response:

You should change the parameter in Postman from image to file as you specify the property name in the POST endpoint:

// you specify the `file` as the fieldname
Router.post('/logo', upload.single('file'), (req, res) => {
    console.log("working");
    //res.json({ file: req.file });
    res.send("done");
  });

From the docs:

.single(fieldname):

Accept a single file with the name fieldname. The single file will be stored in req.file.

  • Related