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?
It might be that you need to remove body parser
delete app.use(express.bodyParser());
I had the same problem when using Next.js API routes with Formidable. Like the other 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,
},
};
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) { });
});
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