2017-07-20 128 views
0

我的REST API應該發送一個文件到另一個API,我不知道如何解決它。我從端點API唯一得到的是這樣的curl命令:nodejs上傳文件使用REST

curl -i -X POST --data-binary @localimg.jpg --header 
"X-API-PersonalKey: XXXX-XXXX-XXXX-XXXX" --header "ContentType:application/octet-stream" 
http://XXX.XX/..../upload 

(順便說一句我有捲曲或此功能沒有EXP,所以我必須學會的飛行。)

我搜查,發現帶有文件系統Readstream並請求POST的教程。

我的解決辦法是這樣的(並且忽略了最低工作)

 var fs = require('fs'); 
     var url = "http://XXX.XX/..../upload"; 
      console.log(url); 
     var fdata = fs.createReadStream("c:/xxx/xxx/localimage.jpg"); 
      console.log(fdata); 
     var options = { 
        url: url, 
        headers: { 
         'X-API-PersonalKey': authToken, 
         "Content-Type": "application/octet-stream" 
        }, 
        data: fdata, 
        body: fdata 

       }; 
     request.post(options, function optionalCallback(err, httpResponse, body) { 
     if (err) { 
      return console.error('upload failed:', err); 
       } 
     console.log("httpRes =" + httpResponse); 
     console.log('Upload successful! Server responded with:', body);  
       }); 
+0

考慮使用https://www.npmjs.com/package/formidable –

+0

我有強大的嘗試,但留在請求。有一點tweeking,它運作良好:-) Ty Jarek – Ckappo

回答

0

你的節點服務器上接收文件,並需要將其保存到磁盤? 如果是,那麼這可能會提供一個提示。

if (request.method == 'POST') { // and you know it is an upload 
    var body = ''; 
    request.on('data',function(data) { body += data; }); 
    request.on('end', function(data) { 
     require('fs').writeFile("c:/xxx/xxx/localimage.jpg", data); 
    }); 
}