requests.post 没有将我的字符串传递到我的文件内容中
requests.post isn't passing my string into the contents of my file
我正在使用接受文本文件上传的 node.js restify 服务器代码和上传文本文件的 python 客户端代码。
这是相关的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
应该出现,但没有出现。代码有什么问题?不知道是服务端还是客户端,还是两个代码都错了。
看起来您正在创建一个文件,但从未真正获取上传的文件内容。在 http://restify.com/#bundled-plugins 查看 bodyParser 示例。您需要为 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);
我正在使用接受文本文件上传的 node.js restify 服务器代码和上传文本文件的 python 客户端代码。
这是相关的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
应该出现,但没有出现。代码有什么问题?不知道是服务端还是客户端,还是两个代码都错了。
看起来您正在创建一个文件,但从未真正获取上传的文件内容。在 http://restify.com/#bundled-plugins 查看 bodyParser 示例。您需要为 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);