大佬教程收集整理的这篇文章主要介绍了使用Node.js将二进制数据推送到Amazon S3,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
curl -kvX POST –data-binary“@ test.jpg”’http:// localhost:3031 / upload / image’
然后在Node.js端,我这样做:
exports.pushImage = function(req,res) { var image = new Buffer(req.body); var s3bucket = new AWs.S3(); s3bucket.createBucket(function() { var params = {Bucket: 'My/bucket',Key: 'test.jpg',Body: imagE}; // Put the object into the bucket. s3bucket.putObject(params,function(err) { if (err) { res.writeHead(403,{'Content-Type':'text/plain'}); res.write("Error uploading data"); res.end() } else { res.writeHead(200,{'Content-Type':'text/plain'}); res.write("success"); res.end() } }); }); };
我的文件是0个字节,如Amazon S3所示.如何使它能够使用Node.js将二进制文件推送到S3?二进制数据和缓冲区我做错了什么?
更新:
我发现我需要做什么卷曲查询是应该改变的第一件事情.这是工作的:
curl -kvX POST -F foobar=@my_image_name.jpg’http:// localhost:3031 / upload / image’
exports.pushImage = function(req,res) { var image = new Buffer(req.body); var s3bucket = new AWs.S3(); s3bucket.createBucket(function() { var bodyStream = fs.createReadStream(req.files.foobar.path); var params = {Bucket: 'My/bucket',Body: bodyStream}; // Put the object into the bucket. s3bucket.putObject(params,{'Content-Type':'text/plain'}); res.write("success"); res.end() } }); }); };
因此,为了将文件上传到API端点(使用Node.js和Express)并将API推送到Amazon S3,首先需要执行POST请求,并填充“files”字段.该文件最终在API端,它所在的位置可能在某个tmp目录中.亚马逊的S3 putObject方法需要一个Stream,因此您需要通过给“fs”模块创建上传文件所在的路径来创建一个读取流.
我不知道这是否是上传数据的正确方式,但它是有效的.有没有人知道有没有办法在请求体内POST二进制数据,并将API发送到S3?我不太了解多部分上传与标准POST到正文之间的区别.
在花费相当多的时间推动资产到S3后,我最终使用了AwsSum库,在生产中取得了极好的成绩:
https://github.com/awssum/awssum-amazon-s3/
(请参阅有关设置您的AWS凭据的文档)
var fs = require('fs'); var bucket_name = 'your-bucket name'; // AwsSum also has the API for this if you need to create the buckets var img_path = 'path_to_file'; var filename = 'your_new_filename'; // using stat to get the size to set contentLength fs.stat(img_path,function(err,file_info) { var bodyStream = fs.createReadStream( img_path ); var params = { BucketName : bucket_name,ObjectName : filename,ContentLength : file_info.size,Body : bodyStream }; s3.putObject(params,data) { if(err) //handle var aws_url = 'https://s3.amazonaws.com/' + DEFAULT_BUCKET + '/' + filename; }); });
因此,如果您使用基于Formidable的Express或Connect类似的功能,那么当Formidable将文件写入磁盘时,您就无法访问文件流.因此,取决于您如何在客户端上传图像,或者是req.body或req.files.在我的情况下,我使用Express,在客户端,我发布其他数据,所以图像有它自己的参数,并被访问为req.files.img_data.但是,您访问它,该参数是您在上述示例中作为img_path传递的参数.
如果您需要/想要将文件转换为棘手的技巧,尽管当然可能,如果您没有操纵图像,您可能需要考虑采用CORS方法并直接上传到S3,如下所述:Stream that user uploads directly to Amazon s3
以上是大佬教程为你收集整理的使用Node.js将二进制数据推送到Amazon S3全部内容,希望文章能够帮你解决使用Node.js将二进制数据推送到Amazon S3所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。