Formidable always returns empty fields and files when I upload a file in Node.js

5.2k views Asked by At

Basically I want to upload a csv file from local computer and parse it in the backend to do required operations. I'm attaching the csv file in the front end. Checked that its not empty. But I'm unable to fetch the same in the server. Is there something I'm missing or doing in the wrong way?

Here is what I have tried till now.

Front end code:

   <form id="myForm" method="POST" enctype="multipart/form-data" action='/testcsv' >
            <input type="file" id="file"  />
            <input type="submit" value="Submit">
   </form>

Backend Code:

 var express = require('express');
 var methodOverride = require('method-override');
 var http = require('follow-redirects').http;    
 var formidable = require('formidable');
 var app = express();
 const fs = require('fs');
 app.use(methodOverride('_method'));

 var bodyParser = require('body-parser');
 app.use(bodyParser.json()); // support json encoded bodies
 app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies



 app.post('/testcsv', requireLogin,  function(req, res) {

 var form = new formidable.IncomingForm();

 form.parse(req, function(err, fields, files) {

    console.log(err);
    console.log(fields);
    console.log(files);

  });

});

Log Output:

 null
 {}
 {}
1

There are 1 answers

0
shaochuancs On

This problem is caused by Frontend code, it has nothing to do with Backend code (formidable).

For the following console.log statement:

console.log(err);
console.log(fields);
console.log(files);
  • err is null because there is no error.
  • fields is {} because in the form, all input fields are file selector. fields in formidable only indicate plain input field, such as <input type="text">.
  • files is {} because the name of file selector in the form is missing.

To get expected value, here is an example form:

<form id="myForm" method="POST" enctype="multipart/form-data" action='/testcsv' >
        <input type="text" name="testtext" />
        <input type="file" id="file" name="testfile" />
        <input type="submit" value="Submit">
</form>

The console.log result for above form would be:

null
{ testtext: '....' }
{ testfile: File....}