2017-10-06 127 views
1

我使用ng-file-upload指令從我的角度應用程序發送圖像到服務器。這裏是我的代碼:上傳分塊圖像文件問題

Upload.upload({ 
    url: 'http://localhost:5000/upload', 
    data: { file: blobFile }, 
    resumeChunkSize: 10000, 
}).then(function (resp) { //upload function returns a promise 
    console.log('resp: ', resp); 
}); 

圖像正在以塊傳輸。但現在,我感到震驚。我不知道如何接收這些塊併合並以創建完整圖像。我的服務器代碼如下:

handler: function (req, res) { 
    var size = 0; 

    req.on('data', function (data) { 
     size += data.length; 
     console.log('Got chunk: ' + data.length + ' total: ' + size); 
    }); 

    req.on('end', function() { 
     console.log("total size = " + size); 
     res.send("response"); 
    }); 

    req.on('error', function (e) { 
     console.log("ERROR ERROR: " + e.message); 
    }); 
    } 

每到這時,我收到塊體請求,req.on('end', ...)觸發器。我是一個在這裏很混亂的新手。

回答

0

是..一個分塊圖像並非如此簡單上傳...

這裏的解決方案,我使用:

var request = require('request'); 
var fs = require('fs'); 

function uploadChunkedImage(url, callback){ 

    // request options 
    var options = { 
     url: url, // the url of the image 
     method: 'GET' 
    }; 

    // array of chunks 
    var chunks = []; 

    // request 
    request(options, function (err, res, body) { 
     console.log('END') 

     // body is corrupted, you can't use it for images... :-(
     // so, we will callback the concactened buffer of it instead 

     // concact chunk buffers 
     chunks = Buffer.concat(chunks); // image buffer that you can use 

     // callback the result 
     callback(err, res, chunks); 

    }).on('response', function (response) { 

     response.on('data', function (chunk) { 
      // collect chunk buffer 
      chunks.push(chunk); 
     }); 

    }); 
} 

uploadChunkedImage('http://localhost:5000/upload', function(err, res, buffer){ 
    if(!err){ 
     // save 
     fs.writeFile('./myDirPath/image.jpg', buffer); 
    }else{ 
     console.log(err); 
    } 

}); 

不要忘了在你的項目有安裝requestfs NPM,Buffer原產

npm install request --save 
npm install fs --save 

更多信息:

您可以用NG-文件上傳做同樣的伎倆,有good example right here,否則我建議你可以試試下面(未測試)

handler: function (req, res) { 

    // array of chunks 
    var chunks= []; 

    req.on('data', function (data) { 

     // collect 
     chunks.push(data); 
     console.log('Got chunk: ' + data.length); 

    }); 

    req.on('end', function() { 

     // concact 
     chunks = Buffer.concat(chunks); 
     console.log("Total size = " + chunks.length); 

     // res.send() is deprecated, use res.write instead 
     res.write(chunks,'binary'); 
     res.end(null, 'binary'); 

    }); 

    req.on('error', function (e) { 
     console.log("ERROR ERROR: " + e.message); 
    }); 
} 

希望能幫到