2013-09-21 30 views
3

從Node.js的HTTP庫文檔:如何使用節點http庫中的發佈請求上傳文件?

http.request() returns an instance of the http.ClientRequest class. 
The ClientRequest instance is a writable stream. If one needs to upload a file 
with a POST request, then write to the ClientRequest object. 

但是我不確定如何在我當前的代碼利用此:

var post_data = querystring.stringify({ 
    api_key: fax.api_key, 
    api_secret: fax.api_secret_key, 
    to: fax.fax_number, 
    filename: "" 
}); 

var options = { 
    host: p_url.hostname.toString(), 
    path: p_url.path.toString(), 
    method: 'POST', 
    headers: { 
      'Content-Type': 'application/x-www-form-urlencoded', 
      'Content-Length': post_data.length 
    } 
}; 

var postReq = http.request(options, function(res) { 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
      console.log('Response: ' + chunk); 
    }); 
}); 

postReq.write(post_data); 
postReq.end(); 

回答

6

既然你有寫流,則可以使用write(),end()pipe()方法。因此,你可以打開一個資源,管它到寫流:

var fs = require('fs'); 
var stream = fs.createReadStream('./file'); 
stream.pipe(postReq); 

或者是這樣的:

var fs = require('fs'); 
var stream = fs.createReadStream('./file'); 

stream.on('data', function(data) { 
    postReq.write(data); 
}); 

stream.on('end', function() { 
    postReq.end(); 
}); 
+0

但等待..是不是'data'請求主體?我如何獲得文件/圖像和使用身體參數(我的表單數據)? – IvRRimUm