2016-10-20 6 views
0

私は、ユーザがアップロードしたファイルを保存するためのAPIを開発中です。NodeJS - 画像バイナリファイルの読み取り

function uploadPhoto(req, res) { 
    var imagedata = new Buffer(''); 

    req.body.on('data', function (chunk) { 
     imagedata = Buffer.concat([imagedata, chunk]); 
    }); 
    req.body.on('end', function (chunk) { 
     fs.writeFile('success.jpeg', imagedata, 'binary', function (err) { 
      if (err) throw err 
      console.log('File saved.') 
     }) 
    }); 
} 

req.body.on( 'data')を使用するとエラーが発生します。郵便配達から データ enter image description hereenter image description here

Iのはconsole.log( "メッセージ:" + req.body)とreq.bodyの値を印刷する場合、それは文字列であり、値を有する: enter image description here

私は、異なるサイズのいくつかのJPEGファイルを作成します。この

var writeFile = function (type, cb) { 
    var data = new Buffer(req.body, type); 
    fs.writeFile(type + '.jpeg', data, type, function (err) { 
     cb(null, data.length); 
    }); 
} 
async.parallel([ 
     writeFile.bind(null, 'binary'), 
     writeFile.bind(null, 'utf8'), 
     writeFile.bind(null, 'ascii'), 
     writeFile.bind(null, 'ucs2'), 
     writeFile.bind(null, 'base64') 
    ], function (err, results) { 
     response.status(200).send({}); 
    }) 

このようにバッファを使用してファイルに書き込もうとしましたが、イメージとしてそれらを読むことができません。

この画像はどのようにユーザーから保存できますか? ありがとうございます。

答えて

0

これはストリームの場合によく似ています。

function uploadPhoto(req, res) { 
    var file = fs.createWriteStream(__dirname + '/success.jpeg') 
    req.pipe(file).on('error', function(err) { console.log(err) }) 
} 

ヘッダーは、ファイルの種類と文字エンコーディングを判別するのにも役立ちます。

var file = fs.createWriteStream(__dirname + '/success.jpeg', {defaultEncoding: req.headers.encoding || 'utf8'}) 
関連する問題