我试图通过curl --upload-file上传文件 由于某种原因,卷曲冻结和upload.backup被创建为空。有关如何更改此代码以使其工作的任何想法?我一定是误解了API
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(request, response) {
var fileBackup = fs.createWriteStream("upload.backup");
var fileBytes = request.headers['content-length'];
var uploadedBytes = 0;
request.on('readable', function() {
var chunk = null;
while (null !== (chunk = request.read())) {
uploadedBytes += chunk.length;
var progress = uploadedBytes / fileBytes * 100;
response.write("progress: " + parseInt(progress, 10) + "%\n");
}
});
request.pipe(fileBackup);
}).listen(8080);
答案 0 :(得分:1)
一个问题是您没有结束您的回复。其次,您可以在将数据写入文件之前从请求流中读取数据。
尝试这样的事情:
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(request, response) {
var fileBackup = fs.createWriteStream('upload.backup');
var fileBytes = parseInt(request.headers['content-length'], 10);
var uploadedBytes = 0;
request.pipe(fileBackup);
if (!isNaN(fileBytes)) {
request.on('data', function(chunk) {
uploadedBytes += chunk.length;
response.write('progress: ' + (uploadedBytes / fileBytes * 100) + '%\n');
});
}
request.on('end', function() {
response.end();
});
}).listen(8080);