0

How do I send a file to Node.js AND parameter data in POST. I am happy to use any framework. I have attempted it with formidable but I am happy to change.

In my attempt, the file sends, but req.body is empty

Python code to upload:

   with open('fileName.txt', 'rb') as f: 
        payLoad = dict()
        payLoad["data"] = "my_data"
        r = requests.post('http://xx.xx.xx.xx:8080/sendFile',json = payLoad, files={'fileName.txt': f})

Server Side Node.js:

var express = require('express');
var formidable = require('formidable');
var app = express();
var bodyParser = require('body-parser');

app.use( bodyParser.json() ); 
app.use(bodyParser.urlencoded({ extended: false })); 

app.post('/sendFile', function (req, res){
    console.log(req.body )
    // req.body is empty
0

1 Answer 1

1

I don't know how to correctly send the file using python, but to receive file with node.js you can use express-fileupload

var fileUpload = require('express-fileupload');
app.use(fileUpload());

app.post('/upload', function(req, res) {
  if (!req.files)
    return res.status(400).send('No files were uploaded.');

  // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file 
  let sampleFile = req.files.sampleFile;

  // Use the mv() method to place the file somewhere on your server 
  sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });
});

https://www.npmjs.com/package/express-fileupload

Sign up to request clarification or add additional context in comments.

8 Comments

Formidable works for the file upload - its sending the other data that is the problem. Does fileupload let you send data?
files = {'upload_file': open('file.txt','rb')} values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'} r = requests.post(url, files=files, data=values)
to receive in node. files req.files.upload_file; params req.body.DB
express-fileupload middleware places the file into req.files, the bodyparser middleware places post params into req.body
No, the req.body is empty
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.