简体   繁体   中英

Uploading file and data from Python to Node.js in POST

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

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

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