17

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?

Jacob
  • 1,577
  • 8
  • 24
R J.
  • 1,522
  • 10
  • 25
  • 40

6 Answers6

30

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,
  },
};
Jacob
  • 1,577
  • 8
  • 24
12

It might be that you need to remove body parser

delete app.use(express.bodyParser());
Marwan Roushdy
  • 1,214
  • 12
  • 25
1

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

Falko
  • 17,076
  • 13
  • 60
  • 105
tolgaio
  • 3,206
  • 1
  • 19
  • 18
1

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) { });
});
jerone
  • 16,206
  • 4
  • 39
  • 57
1

I forgot to add enctype="multipart/form-data" to my html form, maybe this will help somebody :)

Tim Haag
  • 11
  • 1
  • 2
  • That is a pretty general pitfall: please argue why this might well have been the problem here, given the absence of client side code. – greybeard Mar 23 '20 at 21:46
0

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!

Tyler2P
  • 2,324
  • 26
  • 22
  • 31