如何从的FileReader图像上传到Amazon S3,采用流星 [英] How to Upload images from FileReader to Amazon s3, using meteor

查看:166
本文介绍了如何从的FileReader图像上传到Amazon S3,采用流星的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着去建立一个图片上传与流星到Amazon S3。由于休伯特OG,香港专业教育学院发现 AWS-SDK 这让事情变得简单。

我的问题是,上传的数据似乎已损坏。当我下载它说该文件,该文件可能已损坏。也许这就是。

插入数据转换成图像的src,不工作,并且图像的preVIEW显示为它应该,所以原来的文件,并且可能是数据是正确的。

我加载使用的FileReader文件,而且比结果传递数据AWS-SDK putObject方法。

  var文件= template.find('[type = file])的文件[0]。
        VAR键=上传/+ file.name;

        VAR读卡器=新的FileReader();
        reader.onload =功能(事件){
            VAR数据= event.target.result;
            。template.find(IMG)SRC =数据;
            Meteor.call(upload_to_s3文件,上传,reader.result);
        };

        reader.readAsDataURL(文件);
 

和此是服务器上的方法:

 upload_to_s3:功能(文件,文件夹,数据){
        S3 =新AWS.S3({端点:EP});
        s3.putObject(
            {
                斗:myportfoliositebucket
                ACL:大众阅读,
                重点:文件夹+/+ file.name,
                ContentType的:file.type,
                正文:数据
            },
            功能(ERR,数据){
                如果(ERR){
                    的console.log('上传错误:',ERR);
                }其他{
                    的console.log(上传是succesfull,数据);
                }
            }
        );
    }
 

解决方案

我包的NPM模块作为智能包装在这里找到:的 https://atmosphere.meteor.com/package/s3policies

有了它,你可以做一个流星方法返回一个写入策略,并根据该政策,你可以使用Ajax调用上传到S3。

例如:

  Meteor.call(s3Upload',名称,功能(错误的政策){
    如果(错误)
        onFinished({错误:错误});
    VAR FORMDATA =新FORMDATA();
    formData.append(AWSAccessKeyId,policy.s3Key);
    formData.append(政策,policy.s3PolicyBase64);
    formData.append(签名,policy.s3Signature);

    formData.append(钥匙,policy.key);
    formData.append(内容类型,policy.mimeType);
    formData.append(以acl,私人);
    formData.append(文件,文件);

    $阿贾克斯({
        网址:https://s3.amazonaws.com/+ policy.bucket +'/',
        键入:POST,
        XHR:函数(){//自定义XHR
            变种myXhr = $ .ajaxSettings.xhr();
            如果(myXhr.upload){//检查是否上传属性存在
                myXhr.upload.addEventListener(进步,
                    功能(E){
                        如果(e.lengthComputable)
                            onProgressUpdate(e.loaded / e.total * 100);

                }, 假); //处理上传的进度
            }
            返回myXhr;
        },
        成功:函数(){
            //文件完成上传
        },
        错误:函数(){onFinished({错误:参数[1]}); },
        过程数据:假的,
        的contentType:假的,
        //表单数据
        数据:FORMDATA,
        缓存:假的,
        xhrFields:{withCredentials:真},
        数据类型:XML
    });
});
 

编辑:

文件变量行: formData.append(文件,文件); 是类似这样的一行: var文件=的document.getElementById('文件上传')文件[0];

在服务器端code是这样的:

  Meteor.methods({
    s3Upload:函数(名){
        VAR myS3 =新s3Policies(我的钥匙,我的秘密钥匙);

        。VAR位置= Meteor.userId()+/+时刻()格式(MMM DD YYYY)取代(/ \ s + /克,'_')+'/'+名;
        如果(Meteor.userId()){
            VAR斗='我斗;
            VAR政策= myS3.writePolicy(位置,斗,10,4096);
            policy.key =位置;
            policy.bucket =桶;
            policy.mimeType = mime.lookup(名称);
            退货政策;
        }
    }
});
 

Im trying to build an image uploader with meteor to Amazon S3. Thanks to Hubert OG, Ive found AWS-SDK which makes things easy.

My problem is that the data uploaded seems to be corrupt. When I download the file it says, the file may be corrupt. Probably it is.

Inserting the data into an image src, does work, and the preview of the image shows up as it supposed to, so the original file, and probably the data is correct.

I'm loading the file with FileReader, and than pass the result data to AWS-SDK putObject method.

        var file=template.find('[type=file]').files[0];
        var key="uploads/"+file.name;

        var reader=new FileReader();
        reader.onload=function(event){
            var data=event.target.result;
            template.find('img').src=data;
            Meteor.call("upload_to_s3",file,"uploads",reader.result);
        };

        reader.readAsDataURL(file);

and this is the method on the server:

    "upload_to_s3":function(file,folder,data){
        s3 = new AWS.S3({endpoint:ep});
        s3.putObject(
            {
                Bucket: "myportfoliositebucket",
                ACL:'public-read',
                Key: folder+"/"+file.name,
                ContentType: file.type,
                Body:data
            },
            function(err, data) {
                if(err){
                    console.log('upload error:',err);
                }else{
                    console.log('upload was succesfull',data);
                }
            }
        );
    }

解决方案

I wrapped an npm module as a smart package found here: https://atmosphere.meteor.com/package/s3policies

With it you can make a Meteor Method that returns a write policy, and with that policy you can upload to S3 using an ajax call.

Example:

Meteor.call('s3Upload', name, function (error, policy) {
    if(error)
        onFinished({error: error});
    var formData = new FormData();
    formData.append("AWSAccessKeyId", policy.s3Key);
    formData.append("policy", policy.s3PolicyBase64);
    formData.append("signature", policy.s3Signature);

    formData.append("key", policy.key);
    formData.append("Content-Type", policy.mimeType);
    formData.append("acl", "private");
    formData.append("file", file);

    $.ajax({
        url: 'https://s3.amazonaws.com/' + policy.bucket + '/',
        type: 'POST',
        xhr: function() {  // custom xhr
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // check if upload property exists
                myXhr.upload.addEventListener('progress',
                    function (e){
                        if(e.lengthComputable)
                            onProgressUpdate(e.loaded / e.total * 100);

                }, false); // for handling the progress of the upload
            }
            return myXhr;
        },
        success: function () {
            // file finished uploading
        },
        error: function () { onFinished({error: arguments[1]}); },
        processData: false,
        contentType: false,
        // Form data
        data: formData,
        cache: false,
        xhrFields: { withCredentials: true },
        dataType: 'xml'
    });
});

EDIT:

The "file" variable in the line: formData.append("file", file); is from a line similar to this: var file = document.getElementById('fileUpload').files[0];

The server side code looks like this:

Meteor.methods({
    s3Upload: function (name) {
        var myS3 = new s3Policies('my key', 'my secret key');

        var location = Meteor.userId() + '/' + moment().format('MMM DD YYYY').replace(/\s+/g, '_') + '/' + name;
        if(Meteor.userId()) {
            var bucket = 'my bucket';
            var policy = myS3.writePolicy(location, bucket, 10, 4096);
            policy.key = location;
            policy.bucket = bucket;
            policy.mimeType = mime.lookup(name);
            return policy;
        }
    }
});

这篇关于如何从的FileReader图像上传到Amazon S3,采用流星的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆