Search code examples
pythonnode.jsfile-uploadpython-requestsrestify

requests.post isn't passing my string into the contents of my file


I am using a node.js restify server code that accepts text file upload and a python client code that uploads the text file.

Here is the relevant node.js server code;

server.post('/api/uploadfile/:devicename/:filename', uploadFile);

//http://127.0.0.1:7777/api/uploadfile/devname/filename
function uploadFile(req, res, next) {
    var path = req.params.devicename;
    var filename = req.params.filename;

    console.log("Upload file");
    var writeStream = fs.createWriteStream(path + "/" + filename);
    var r = req.pipe(writeStream);

    res.writeHead(200, {"Content-type": "text/plain"});

    r.on("drain", function () {
        res.write(".", "ascii");
    });

    r.on("finish", function () {
        console.log("Upload complete");
        res.write("Upload complete");
        res.end();
    });

    next();
} 

This is the python2.7 client code

import requests

file_content = 'This is the text of the file to upload'

r = requests.post('http://127.0.0.1:7777/api/uploadfile/devname/filename.txt',
    files = {'filename.txt': file_content},
)

The file filename.txt did appear on the server filesystem. However, the problem is that the contents is empty. If things went right, the content This is the text of the file to upload should appear but it did not. What is wrong with the code? I am not sure if it is server or client or both code that are wrong.


Solution

  • It looks like you're creating a file but never actually getting the uploaded file contents. Check out the bodyParser example at http://restify.com/#bundled-plugins. You need to give the bodyParser a function for handling multi-part data.

    Alternatively, you could just use bodyParser without your own handlers and look for the uploaded file information in req.files, including where the temporary uploaded file is for copying to wherever you like.

    var restify = require('restify');
    var server = restify.createServer();
    server.use(restify.bodyParser());
    
    server.post('/upload', function(req, res, next){
       console.log(req.files);
       res.end('upload');
       next();
    });
    
    server.listen(9000);