Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
 {}
 {}
like image 431
Anirudh Avatar asked Oct 14 '25 15:10

Anirudh


1 Answers

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....}
like image 52
shaochuancs Avatar answered Oct 17 '25 10:10

shaochuancs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!