[英]How to stream image to amazon s3 using express js 3.X and angular js?
我已經使用connect-busboy來獲取上載的文件,但是我的腳本沒有發出文件事件。 我在客戶端使用角度。
我正在使用以下代碼:
req.busboy.on('error', function (fieldname, file, filename, encoding, mimetype) { console.log(fieldname); }); req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) { //set aws header var awsHeader = { Bucket: 'Mybucket', Key: 'MyImage', ContentType: mimetype, ACL: 'public-read' }; file.uploadFile(file, awsHeader, function (err, res) { console.log(err); console.log(res); }); }); req.busboy.on('finish', function () { res.send({status: true, message: "File uploaded succesfully."}); }); req.busboy.on('field', function (key, value, keyTruncated, valueTruncated) { console.log(key); }); req.pipe(req.busboy);
每次我嘗試上傳文件時,都會觸發finish事件。
看起來您不是從多部分表單中構建文件。 在下面的代碼之前,我使用節點aws-sdk構建可以放入的s3Bucket。
req.busboy.on ( 'file', function ( fieldname, file, filename, encoding, mimetype ) {
if ( !filename ) {
// If filename is not truthy it means there's no file
return res.status ( 400 ).send ( {error: 'no file'} );
}
// Create the initial array containing the stream's chunks
file.fileRead = [];
file.on ( 'data', function ( chunk ) {
// Push chunks into the fileRead array
this.fileRead.push ( chunk );
//you can use this if you want to limit file size on ingest
/*if(this.fileRead.length > 5500000){
return res.status(500 ).send({error:"file too large - 5MB max"})
}*/
} );
file.on ( 'error', function ( err ) {
console.log ( 'Error while buffering the stream: ', err );
} );
file.on ( 'end', function () {
// Concat the chunks into a Buffer
var finalBuffer = Buffer.concat ( this.fileRead );
req.files[fieldname] = {
buffer : finalBuffer,
size : finalBuffer.length,
filename: filename,
mimetype: mimetype
}
var data = {Key: "users/" + req.body.id + '/image/' + req.body.id, Body: req.files[fieldname].buffer, ACL: 'public-read'};
//im not sure how you're uploading to s3 but I use this
s3Bucket.putObject ( data, function ( err, data ) {
if ( err ) {
console.log ( err )
return res.status ( 400 ).send ( 'error during upload' )
} else { //success
}
} )
} );
} );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.