2015-06-07 65 views
0

我試圖通過curl上傳一個文件--upload-file 出於某種原因,捲曲凍結和upload.backup被創建爲空。任何想法如何改變這個代碼使其工作?我一定是誤解了APIsNode.js - 帶進度的文件上傳

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

回答

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