上传分块的图像文件问题

我正在使用ng-file-upload指令从我的angular度应用程序发送图像到服务器。 这是我的代码:

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

图像正在大块传输。 但现在,我感到震惊 我不知道如何接收这些块并合并来创build一个完整的图像。 我的服务器代码如下:

 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', ...)触发器。 我是一个在这里很困惑的新手。

是的..一个分块的图像不是那么简单的上传…

这里我使用一个解决scheme:

 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); } }); 

不要忘记用npm在你的项目中安装requestfsBuffer是本地的

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

了解更多信息:

  • 请求存储库
  • FS文件

你可以用ng-file-upload做同样的技巧,这里有一个很好的例子 ,否则我build议尝试下面的东西(未testing)

 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); }); } 

希望这会有所帮助