简体   繁体   中英

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.

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)
    })
  })
})

I think you need some middleware to accept the multipart formdata in the server side. Multer is a good option.

You can use

var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

and then update your server side to handle the upload:

app.post('/sendFiles', upload.array('files', maxCount), function(req,res)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM