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