2015-11-18 17 views
0

我使用接受文本文件的上傳和上傳文本文件中的Python客戶端代碼的node.js的RESTify服務器的代碼我的文件的內容。requests.post不通過我的字符串轉換成

下面是相關的node.js服務器代碼;

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

這是python2.7客戶端代碼

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

文件filename.txt沒有出現在服務器的文件系統。但問題是內容是空的。如果事情發生了吧,內容This is the text of the file to upload應該出現,但事實並非如此。代碼有什麼問題?我不確定它是否是服務器或客戶端,或者這兩個代碼都是錯誤的。

+1

請改善您的問題標題,「爲什麼這不工作」是不是一個合適的標題。 – Torxed

+0

你嘗試刪除'下一個()'從'uploadFile()'路由處理的結束? – mscdex

回答

1

它看起來像你創建一個文件,但實際上從未得到上傳的文件內容。查看bodyParser示例,網址爲http://restify.com/#bundled-plugins。您需要爲bodyParser提供處理多部分數據的功能。

或者,你可以只使用bodyParser沒有自己的處理程序,並尋找在req.files上傳的文件信息,包括臨時上傳的文件拷貝到你喜歡的地方。

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