I looked everywhere on internet but I found nothing that looks like my issue. I'm new to Node.JS and I want to upload, with Multer, two different pictures but from the same form. Here's my form:
<form action="/upload" enctype="multipart/form-data" method="post">
<label for="pp_uploader">Add a profile picture</label>
<input type="file" id="pp_uploader" name="pp"/><br>
<label for="banner_uploader">Add a banner</label>
<input type="file" id="banner_uploader" name="banner" /><br>
<input class="sbutton" type="submit" value="Envoyer" />
</form>
Here's the code:
app.post("/upload", function(req, res, fields) {
const storagepp = multer.diskStorage({
destination: "data/pp/",
filename: function(req, file, cb){
cb(null, sess.surname + sess.name + ".jpg");
}
});
const uploadpp = multer({
storage: storagepp
}).single("pp");
uploadpp(req, res, (err) => {
if (err) throw err;
});
const storagebanner = multer.diskStorage({
destination: "data/banner/",
filename: function(req, file, cb){
cb(null, sess.surname + sess.name + ".jpg");
}
});
const uploadbanner = multer({
storage: storagebanner
}).single("banner");
uploadbanner(req, res, (err) => {
if (err) throw err;
});
})
And I'm getting this error:
Error: Unexpected field
at makeError (/home/quentin/Documents/SocialHorse/node_modules/multer/lib/make-error.js:12:13)
at wrappedFileFilter (/home/quentin/Documents/SocialHorse/node_modules/multer/index.js:40:19)
at Busboy.<anonymous> (/home/quentin/Documents/SocialHorse/node_modules/multer/lib/make-middleware.js:114:7)
at Busboy.emit (events.js:160:13)
at Busboy.emit (/home/quentin/Documents/SocialHorse/node_modules/busboy/lib/main.js:38:33)
at PartStream.<anonymous> (/home/quentin/Documents/SocialHorse/node_modules/busboy/lib/types/multipart.js:213:13)
at PartStream.emit (events.js:160:13)
at HeaderParser.<anonymous> (/home/quentin/Documents/SocialHorse/node_modules/dicer/lib/Dicer.js:51:16)
at HeaderParser.emit (events.js:160:13)
at HeaderParser._finish (/home/quentin/Documents/SocialHorse/node_modules/dicer/lib/HeaderParser.js:68:8)
When I use console.log(fields);
I'm getting this: [Function: next]
I also tried to upload only one picture with only one input in my form and it seems to work so I'm probably missing a function which is able to done my work.
Actually, what I wanted to do is to save the two pictures separately in two different folder (which is impossible with Multer) so i found a solution to my problem:
New server-side code:
app.post("/upload", function(req, res, fields) {
const storage = multer.diskStorage({
destination: "public/data/",
filename: function(req, file, cb){
crypto.randomBytes(20, (err, buf) => {
cb(null, buf.toString("hex") + path.extname(file.originalname))
})
}
});
const upload = multer({
storage: storage
}).fields([{name: "pp"}, {name: "banner"}]);
upload(req, res, (err) => {
if (err) throw err;
});
});
Hoping it would help some people !