I'm using Multer to make an upload file system. I followed the instructions of the Github page but it's not working.
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) {
cb(null, file.fieldname + '-' + Date.now());
}
});
const upload = multer({ storage: storage });
app.post('/editPhoto',upload.single('avatar'),function(req,res,next){
upload(req,res,function(err){
if(err){
res.json({success:false,message:err});
}
else{
res.json({success:true,message:"Photo was updated !"});
}
});
});
I get TypeError: upload is not a function
What am I doing wrong ?
EDIT
I did as you said and as the doc says.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now());
}
});
app.post('/editPhoto',function(req,res,next){
var upload = multer({ storage:storage}).single('userPhoto');
upload(req,res,function(err){
console.log(req.file);
if(err){
res.json({success:false,message:err});
}
else{
res.json({success:true,message:"Photo was updated !"});
}
});
});
req.file is undefined
and when i try like this
var upload = multer({ storage:storage});
app.post('/editPhoto',function(req,res,next){
upload(req,res,function(err){
console.log(req.file);
if(err){
res.json({success:false,message:err});
}
else{
res.json({success:true,message:"Photo was updated !"});
}
});
});
I get upload is not a function
file); }); }); Multer supports uploading a single file as well as multiple files. In this case, we have used multer({..}). single() which is used for uploading a single file. As I have mentioned before that the multer adds a file object to the request.
Multer is a node. js middleware for handling multipart/form-data , which is primarily used for uploading files. It is written on top of busboy for maximum efficiency. NOTE: Multer will not process any form which is not multipart ( multipart/form-data ).
Open the local page http://127.0.0.1:2000/ to upload the images. Select an image to upload and click on "Upload Image" button. Here, you see that file is uploaded successfully. You can see the uploaded file in the "Uploads" folder.
As @Aabid told in The comments you will not need to use both, the multer middleware and upload in the controller.
You can use:
app.post('/editPhoto', upload.single('avatar'), (req, res, next) => {
// here in the req.file you will have the uploaded avatar file
})
Or you can use:
app.post('/editPhoto', (req, res, next) => {
upload(req, res, function (err) {
if (err) {
// This is a good practice when you want to handle your errors differently
return
}
// Everything went fine
})
})
So you use one of the 2 methods, not both at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With