Reputation: 411
I created a node API using multer to store files and i'm getting error while calling it, please help. Bellow is the code and error -
Code -
const storage = multer.diskStorage({
destination: './public/upload',
filename: function(req, file, cb){
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// initialize upload
const upload = multer({
storage: storage,
limits: {fieldSize: 100000}
}).single('myImage');
app.post('/upload', (req, res)=> {
upload(req, res, (err) => {
if(err){
res.json({
msg: req.body,
});
}else {
res.json({
msg: 'File uploaded',
file: `upload/${req.file.filename}`
});
}
})
})
The error i'm getting while making API call is "name": "MulterError", "message": "Unexpected field", "code": "LIMIT_UNEXPECTED_FILE", "storageErrors": []
Upvotes: 0
Views: 3259
Reputation: 19
limits: {fileSize: 100000}
I didn't check it but I believe it has to be fileSize not fieldSize, probably
Upvotes: 0
Reputation: 339
On your Frontend code have you made sure the input name is myImage
If you are using HTML try using this code
<input type=“file” name=“myImage” />
Suppose you are using the front end framework react
This piece of code should be in the submit/ uploadFile function
const uploadFile = (e) =>{
e.preventDefault();
let file = e.target.files[0];
let data = new FormData();
data.append('myImage', file);
axios.post('http://localhost:5000/upload', data, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => this.setState({file: res.data.file}));
}
I hope this helps
Upvotes: 0
Reputation: 411
Passing the filename works for me -
uploadFile = (e) =>{
let file = e.target.files[0];
let data = new FormData();
data.append('myImage', file);
axios.post('http://localhost:5000/upload', data, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => this.setState({file: res.data.file}));
}
Upvotes: 1