1

I am trying nodejs for the first time. I am using it with python shell. I am trying to transfer a file from one PC to another using Post request

app.js (Server PC)

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

app.post('/mytestapp', function(req, res) {
    console.log(req)
    var command = req.body.command;
    var parameter = req.body.parameter;
    console.log(command + "|" + parameter)
    pyshell.send(command + "|" + parameter);
    res.send("POST Handler for /create")
});

python file send file from (Client PC)

f = open(filePath, 'rb')
try:
    response = requests.post(serverURL, data={'command':'savefile'}, files={os.path.basename(filePath): f})

I use fiddler and the request seems to contain the file on Client PC, but I can't seem to get the file on Server PC. How can I extract and save the file? Is it because I am missing headers? what should I use? thanks

golu
  • 629
  • 2
  • 7
  • 18

1 Answers1

0

I'm going to guess and say you're using Express based on the syntax in your question. Express doesn't ship with out of the box support for file uploading.

You can use the multer or busboy middleware packages to add multipart upload support.

Its actually pretty easy to do this, here is a sample with multer

const express = require('express')
const bodyParser = require('body-parser')
const multer = require('multer')

const server = express()
const port = process.env.PORT || 1337

// Create a multer upload directory called 'tmp' within your __dirname
const upload = multer({dest: 'tmp'})

server.use(bodyParser.json())
server.use(bodyParser.urlencoded({extended: true}))

// For this route, use the upload.array() middleware function to 
// parse the multipart upload and add the files to a req.files array
server.port('/mytestapp', upload.array('files') (req, res) => {
    // req.files will now contain an array of files uploaded 
    console.log(req.files)
})

server.listen(port, () => {
    console.log(`Listening on ${port}`)
})
peteb
  • 18,552
  • 9
  • 50
  • 62
  • thanks! but from the Client PC (python script), what code would upload the file? – golu Apr 06 '17 at 20:41
  • @golu isnt that a different question from the one you asked about how to handle an uploaded file to a Nodejs server? – peteb Apr 06 '17 at 20:42
  • Yes, maybe so. Do I need a different question for that then? I am also stuck on that part.. – golu Apr 06 '17 at 20:47
  • @golu, I'd say so, how to send a file via HTTP POST request with Python is pretty different from how to handle it server side in Node.js – peteb Apr 06 '17 at 20:48
  • Please answer the followup question here: http://stackoverflow.com/questions/43266317/upload-a-file-to-nodejs-using-python-request. I am getting multer related errors – golu Apr 06 '17 at 22:11