Search code examples
javascriptnode.jsajaxweb-applicationsform-data

FormData server side NodeJS


I'm developing a web application using nodejs server-side. I'm trying to send pdf files from client to server.

Client:

var files = new FormData();
var count = 0;
$('#tableSlideId tr').each(function() {

    var inputForm = $(this).find("th:first").children();
    file = inputForm[0].files[0];
    files.append((count++).toString(),file);

});

$.ajax({
    type: "POST",
    url: "/sendFiles",
    data: files,
    contentType: false,
    processData: false,

}).done(function(err){

    var text ="";
    if(err) {

        text = "Upload FAILED! Retry ...";

    } else {

        text = "Upload SUCCES!";

    }

    alert(text);



});

I think the client side is ok, infact if I use this loop:

for(var p of files)
  console.log(p);

I correctly visualize all the elements that I want to send to the server.

Server:

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

    console.log("--->",req.body);
    res.end();

});

Now in the server I have no idea how to visualize the data that I send, infact req.body is empty.

I don't know if this is the right way but my goal is to load some pdf files form the client, send to the server and after store them in a mySql dmbs. Thank you.


Solution

  • Use express-formidable module. install 'express-formidable' by the running command

    npm install express-formidable --save
    

    a simple example is as follows from github

    
    const express = require('express');
    const formidable = require('express-formidable');
    
    var app = express();
    
    app.use(formidable());
    
    app.post('/upload', (req, res) => {
      //req.fields contains non-file fields 
      //req.files contains files 
      console.log(req.fields);
      console.log(req.files);
    });
    
    

    Hope this helps!

    Edit, from here -

    app.post('/submit-form', (req, res) => {
      new formidable.IncomingForm().parse(req, (err, fields, files) => {
        if (err) {
          console.error('Error', err)
          throw err
        }
        console.log('Fields', fields)
        console.log('Files', files)
        files.map(file => {
          console.log(file)
        })
      })
    })