I have a problem since yesterday with my node express app.
The thing what I want to do is the next one:
Middleware 1, step 1 (parse request): Parse the multipart/form-data in req.body with formidable and do what I want to do with the data (such validation), then go to step 2 if all being good.
Middleware 2, step 2 (upload file): Upload file with formidable (already being parsed)
Problems:
- Multer: Already tested with Multer but impossible, I have to put the middleware 2 before the middleware 1 otherwise the req.body is empty (also tested multer.none()).
- Formidable: Actively testing with formidable but when I parse the request in the Middleware 1, formidable won't do anything in the Middleware 2 (because my req.body is already parsed and he didn't find the file ?)
I know there is a filter function but I really want to have two seperated middlewares.
Express middlewares
const formidable = require('formidable');
// parse request
module.exports.middleware1 = async (req, res, next) => {
const form = formidable({ multiples: true });
form.parse(req, (err, fields, files) => {
if (err) {
next(err);
return;
}
// request parsed
// do what I want to do with the fields (such validation)
console.log(fields)
next()
});
}
// upload file
module.exports.middleware2 = async (req, res, next) => {
const options = {
uploadDir: 'test',
keepExtensions: true,
maxFiles: 1,
filename: function (name, ext, part, form) {
return name
},
filter: function ({name, originalFilename, mimetype}) {
return true
}
}
const form = formidable(options);
form.parse(req, (err, fields, files) => {
if (err) {
next(err);
return;
}
// file uploaded, go to controller
next()
});
}
Front app
publishPost: function () {
let formData = new FormData()
const post = {
filters: {
...this.postFilters
},
details: {
...this.postDetails
}
}
formData.append('post', JSON.stringify(post))
formData.append('file', this.postMedia.file)
postService.createOne(formData).then((res) => {
if (res) {
postServiceStatus.createOneDone()
}
});
}
If anyone has an idea, I'd be grateful!