Reputation: 1542
I am using the formidable
package to handle file uploads on my server.
This is my express.js
app code:
var formidable = require("formidable"),
http = require("http"),
util = require("util");
app.post("/admin/uploads", function (req, res) {
console.log(req.files, req.fields); //It prints
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
console.log("Inside form parse."); //its not printing
console.log(err, fields, files); //its not printing
});
form.on("file", function (name, file) {
console.log("file=" + file);
}); //its not printing
form.on("error", function (err) {
console.log(err);
}); //its not printing
form.on("aborted", function () {
console.log("Aborted");
}); //its not printing
console.log(form); //it prints
});
In the above code, the form.parse
and form.on
callbacks are never run. How can I solve this issue?
Upvotes: 17
Views: 11971
Reputation: 1825
I had the same problem when using Next.js API routes with Formidable. As another answer points out, you have to remove the body parser. In Next.js, you can export a config
object and disable body parsing.
// /pages/api/form.js
import { IncomingForm } from "formidable";
export default function handler(req, res) {
// formidable logic
}
// VV important VV
export const config = {
api: {
bodyParser: false,
},
};
Note that if your project uses the newer app
router, you won’t need Formidable; you can handle form submissions using FormData
in server actions / mutations.
Upvotes: 33
Reputation: 1
Even if you remove body-parser
and use express.json()
etc... you will have same error.
The problem is that express.raw()
is causing trouble remove it and it works!
Upvotes: 0
Reputation: 11
I forgot to add enctype="multipart/form-data" to my html form, maybe this will help somebody :)
Upvotes: 1
Reputation: 3246
Please add the error handlers and send the error message otherwise it is hard to get an answer.
form.on('error', function(err) { console.log(err); });
form.on('aborted', function() { console.log('Aborted'); });
See the formidable
documentation : doc
Upvotes: 1
Reputation: 16861
Call form.parse(...)
after all on(...)
events.
app.post('/admin/uploads', function(req, res) {
var form = new formidable.IncomingForm();
form.on('file', function(name, file) { });
form.on('error', function(err) { });
form.on('aborted', function() { });
form.parse(req, function(err, fields, files) { });
});
Upvotes: 1
Reputation: 1230
It might be that you need to remove body parser
delete app.use(express.bodyParser());
Upvotes: 13