2017-04-20 119 views
1

我試圖發送文件到另一個node.js服務。因此,我使用http和表單數據模塊。Nodejs通過http發送文件

這是我寫

function uintToString(uintArray) { 
    return String.fromCharCode.apply(null, new Uint8Array(uintArray)); 
} 


function (file) {  
    var data = uintToString(file.buffer); 
// 
var crlf = "\r\n", 
    boundaryKey = Math.random().toString(16), 
    boundary = `--${boundaryKey}`; 
    delimeter = `${crlf}--${boundary}`, 
    preamble = "", // ignored. a good place for non-standard mime info 
    epilogue = "", 
    headers = [ 
     'Content-Disposition: form-data; name="file"; filename="' + name + '"' + crlf 
    ], 
    closeDelimeter = `${delimeter}--`, 
    multipartBody = Buffer.concat(
     new Buffer(preamble + delimeter + crlf + headers.join('') + crlf), 
     data, 
     new Buffer(closeDelimeter + epilogue) 
    ); 


    var options = { 
     host: 'localhost', 
     port: 3000, 
     method: 'POST', 
     path: '/data/get', 
     headers: { 
      'Content-Type': 'multipart/form-data; boundary=' + boundary, 
      'Content-Length': formData._valueLength 
     } 
    }; 

    //make request 
    return httpsRequest(formData, options) 
     .then((result) => { 

      console.log(result); 
     }, (err) => { 

      console.log(err); 

     }); 
}; 


function httpsRequest(data, options) { 

    return new Promise(function (resolve, reject) { 
     // request object 
     var req = https.request(options, function (res) { 
      var result = ''; 
      res.on('data', function (chunk) { 
       result += chunk; 
      }); 
      res.on('end', function() { 
       console.log("https end result - " + result); 
       resolve(result); 
      }); 
      res.on('error', function (err) { 
       reject(err); 
      }) 
     }); 

     // req error 
     req.on('error', function (err) { 
      reject(err); 
     }); 

     //send request witht the postData form 
     req.write(data); 
     req.end(); 

    }); 
} 

這是給""list" argument must be an Array of Buffers"此錯誤代碼。它看起來像在httpsRequest函數上有問題。

回答

0

不要重新發明輪子,needle/request可以爲你做到這一點。如果你想promisify東西,使用bluebird

const Promise = require('bluebird') 
const needle = Promise.promisifyAll(require('needle')) 

function send (file) { 
    let url = 'https://localhost/data/get' 
    let data = { 
    zip_file: { 
     buffer  : file.buffer, 
     filename  : name, 
     content_type : 'application/octet-stream' 
    } 
    } 

    return needle.postAsync(url, data, { multipart: true }) 
}