如何使用 Meteor 将文件上传到 Amazon S3

How to upload files to Amazon S3 with Meteor?

本文关键字:Amazon S3 文件 何使用 Meteor      更新时间:2023-09-26

我正在尝试将文件上传到我的 Amazon S3 存储桶。S3 和亚马逊已设置。这是来自亚马逊的错误消息:

冲突的查询字符串参数:ACL、策略

策略和签名对节点进行编码,使用加密.js.js

var crypto=Npm.require("crypto");

我正在尝试使用 Meteor HTTP.post 方法构建 POST 请求。这也可能是错误的。

    var BucketName="mybucket";
    var AWSAccessKeyId="MY_ACCES_KEY";
    var AWSSecretKey="MY_SECRET_KEY";
    //create policy
    var POLICY_JSON={
        "expiration": "2009-01-01T00:00:00Z",
            "conditions": [ 
            {"bucket": BucketName}, 
            ["starts-with", "$key", "uploads/"],
            {"acl": 'public-read'},
            ["starts-with", "$Content-Type", ""],
            ["content-length-range", 0, 1048576],
        ]   
    }
    var policyBase64=encodePolicy(POLICY_JSON);
    //create signature
    var SIGNATURE = encodeSignature(policyBase64,AWSSecretKey);
    console.log('signature: ', SIGNATURE);

这是我与 Meteor 一起使用的 POST 请求:

    //Send data----------
    var options={
        "params":{
            "key":file.name,
            'AWSAccessKeyId':AWSAccessKeyId,
            'acl':'public-read',
            'policy':policyBase64,
            'signature':SIGNATURE,
            'Content-Type':file.type,
            'file':file,
            "enctype":"multipart/form-data",
        }
    }
    HTTP.call('POST','https://'+BucketName+'.s3.amazonaws.com/',options,function(error,result){
        if(error){
            console.log("and HTTP ERROR:",error);
        }else{
            console.log("result:",result);
        }
    });

她的 我正在编码策略和签名:

encodePolicy=function(jsonPolicy){
    // stringify the policy, store it in a NodeJS Buffer object
    var buffer=new Buffer(JSON.stringify(jsonPolicy));
    // convert it to base64
    var policy=buffer.toString("base64");
    // replace "/" and "+" so that it is URL-safe.
    return policy.replace(/'//g,"_").replace(/'+/g,"-");
}
encodeSignature=function(policy,secret){
    var hmac=crypto.createHmac("sha256",secret);
    hmac.update(policy);
    return hmac.digest("hex");
}

A无法弄清楚发生了什么。POST 方法或加密可能已经存在问题,因为我不太了解这些方法。如果有人能为我指出正确的方向、编码或正确地向 AmazonS3 发送 POST 请求,这可能会有很大帮助。
(我不喜欢使用 filepicker.io,因为我不想强迫客户也在那里注册。

提前谢谢!!

直接上传到 S3 您可以使用弹弓包:

meteor add edgee:slingshot

在服务器端声明您的指令:

Slingshot.createDirective("myFileUploads", Slingshot.S3Storage, {
  bucket: "mybucket",
  allowedFileTypes: ["image/png", "image/jpeg", "image/gif"],
  acl: "public-read",
  authorize: function () {
    //You can add user restrictions here
    return true;
  },
  key: function (file) {
    return file.name;
  }
});

此指令将自动生成策略和签名。

他们只是像这样上传它:

var uploader = new Slingshot.Upload("myFileUploads");
uploader.send(document.getElementById('input').files[0], function (error, url) {
  Meteor.users.update(Meteor.userId(), {$push: {"profile.files": url}});
});

为什么不使用 aws-sdk 软件包?它为您打包了所有需要的方法。例如,下面是将文件添加到存储桶的简单函数:

s3.putObject({
  Bucket: ...,
  ACL: ...,
  Key: ...,
  Metadata: ...,
  ContentType: ...,
  Body: ...,
}, function(err, data) {
  ...
});

查看S3流星包。自述文件有一个非常全面的入门演练

第一件事是为 s3 文件上传添加包。

对于安装:添加(AWS 开发工具包智能程序包) $ meteor add peerlibrary: aws-sdk

1.创建指令上传.js并粘贴此代码。

angular.module('techno')
.directive("fileupload", [function () {
    return {
        scope: {
            fileupload: "="
        },
        link: function(scope,element, attributes){
            $('.button-collapse').sideNav();
            element.bind("change", function (event) {
                scope.$apply(function () {
                 scope.fileupload = event.target.files[0];
             });
           })
       }};
}]);

2.获取访问密钥并将其粘贴到您的fileUpload.js文件中。

AWS.config.update({
accessKeyId: ' AKIAJ2TLJBEUO6IJLKMN ',
secretAccessKey: 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'
});
AWS.config.region = 'us-east-1';
let bucket = new AWS.S3();

3.现在将此上传代码放在您的指令fileUpload.js

vm.upload = (Obj) =>{
vm.loadingButton = true;
let name = Obj.name;
let params = {
    Bucket: 'technodheeraj',
    Key: name,
    ContentType: 'application/pdf',
    Body: Obj,
    ServerSideEncryption: 'AES256'
};
bucket.putObject(params, (err, data) => {
    if (err) {
        console.log('---err------->', err);
    }
    else {
        vm.fileObject = {
            userId: Meteor.userId(),
            eventId: id,
            fileName: name,
            fileSize: fileObj.size,
        };
   vm.call("saveFile", vm.fileObject, (error, result) => {
            if (!error){
                console.log('File saved successfully');
            }
        })
    }
})
};

4.现在在"保存文件"方法中粘贴此代码

saveFile: function(file){
if(file){
    return Files.insert(file);
}
};

5.In HTML 粘贴此代码

<input type="file" name="file" fileupload="file">
<button type="button" class="btn btn-info " ng-click="vm.upload(file)"> Upload File</button>