node通過http.request向其他服務器上傳文件


function upload(callback) {
    let boundaryKey = '----' + new Date().getTime();    // 用於標識請求數據段
    let options = {
        host: 'localhost', // 遠端服務器域名
        port: 80, // 遠端服務器端口號
        method: 'POST',
        path: `/upload`, // 上傳服務路徑
        headers: {
            'Content-Type': 'multipart/form-data; boundary=' + boundaryKey,
            'Connection': 'keep-alive'
        }
    };
    let req = http.request(options, function(res){
        res.setEncoding('utf8');

        res.on('data', function(chunk) {
            console.log('body: ' + chunk);
        });

        res.on('end', function() {
            console.log('res end.');
        });
    });
    /*req.write(
         '--' + boundaryKey + 'rn' +
         'Content-Disposition: form-data; name="upload"; filename="test.txt"rn' +
         'Content-Type: text/plain'
     );*/
    req.write(
        `--${boundaryKey}rn Content-Disposition: form-data; name="${self.path}"; filename="${self.file}"rn Content-Type: text/plain`
    );

    // 創建一個讀取操作的數據流
    let fileStream = fs.createReadStream(this.filePath);
    fileStream.pipe(req, {end: false});
    fileStream.on('end', function() {
        req.end('rn--' + boundaryKey + '--');
        callback && callback(null);
    });
}
參考地址: http://blog.csdn.net/haiyan2012/article/details/8540802
http://www.cnblogs.com/king_domain/p/5630665.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM