0

I am not able to upload the any file or image using multer node package in mac. But same code working fine in windows. I'm using postman for api call. when I hit the api and inside console log Im getting undefined for req.file

const express = require('express');
        const app = express();
        const multer  = require('multer');
        const storage = multer.diskStorage({
           destination: function (req, file, cb) {
             cb(null, 'uploads')
           },
           filename: function (req, file, cb) {
              console.log(file)
           //   const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
             cb(null, file.originalname)
           }
         })
        const upload = multer({storage: storage})
        
        app.post('/post', upload.single('avatar'), (req,res)=>{
    console.log(req.file)
           if (!req.file) {
              return res.status(400).send([{ msg: "File is missing",err }])
            }
        else{
           return res.status(200).send([{ msg: "working", }])
        }
        });
        app.listen(3000,(err,succes)=>{
         if (err) {
            console.log(err)
         }else{
            console.log("Server is running in port number",3000)
         }
        });
3
  • Please have a look at How to Ask. "It doesn't work" is not a question. What exactly is not working? Are you receiving any errors? If so then please add the errors (as text) inside the question
    – DarkBee
    Commented Jun 26 at 5:45
  • Have you actually created the uploads directory? Using the callback for destination requires that you create it manually. Also, follow the error handling guide for debugging hints
    – Phil
    Commented Jun 26 at 6:06
  • Yeah i have created the folder in same path where Index.js is exists. Commented Jun 26 at 6:14

1 Answer 1

0

Can you please write a small Nodejs client and test it. This is to rule out if something specific to postman.

The code below is a sample Nodejs client.

client.js //run it as node client

const fs = require('fs');
const axios = require('axios');
const FormData = require('form-data');

const formdata = new FormData();

// adding the file
formdata.append('avatar', fs.createReadStream('./avatar.jpg'));

axios
  .post('http://localhost:3000/post', formdata)
  .then((data) => {
    console.log(data.data);
  })
  .catch((error) => {
    console.log(error);
  });
2
  • Postman is the problem. By using this method i found out the api is working fine. thank you Commented Jun 26 at 7:04
  • Thank you for your confirmation. It not only brings a formal closure to the question and but also will encourage other info seekers to make use of this content. Commented Jun 26 at 7:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.