简体   繁体   English

AWS S3 同步上传文件

[英]AWS S3 upload file synchronously

I am using Meteor on Server side where I used Method Calls to return data.我在使用方法调用返回数据的服务器端使用 Meteor。

So there I am trying to upload file to AWS S3 Bucket synchronously.所以我正在尝试将文件同步上传到 AWS S3 Bucket。

Here is a sample code:这是一个示例代码:

Meteor.methods({

    uploadImage: function (params) {

        var AWS = Npm.require('aws-sdk');

        AWS.config.loadFromPath(process.env["PWD"]+'/private/awss3/s3_config.json');
        var s3Bucket = new AWS.S3( { params: {Bucket: 'users-profile-pictures'} } );

        buf = Buffer.from(params.baseimage.replace(/^data:image\/\w+;base64,/, ""),'base64')
        var data = {
          Key: params.fileName, 
          Body: buf,
          ContentEncoding: 'base64',
          ContentType: 'image/jpeg'
        };

        s3Bucket.putObject(data, function(err, data){
            if (err) { 
              console.log(err);
              console.log('Error uploading data: ', data); 
            } else {
              console.dir(data);
              console.log('successfully uploaded the image!');
            }
        });

        return data;
    },
});

Now here I want to return the response I got from AWS SDK Callback.现在,我想返回从 AWS SDK 回调得到的响应。 How can I make this upload synchronously?我怎样才能使这个上传同步?

I'm not expert with AWS SDK, but for my experience, all internet requests are asyncronous, because server take time to respond.我不是 AWS SDK 方面的专家,但根据我的经验,所有互联网请求都是异步的,因为服务器需要时间来响应。 Anyway, you need to use it as you are currently using, or you need to do all your script asyncronous and then add the await tag to await the function output: await s3Bucket.putObject(... .无论如何,您需要按照当前使用的方式使用它,或者您需要将所有脚本异步执行,然后添加 await 标记以等待 function output: await s3Bucket.putObject(... .

In Meteor you use wrapAsync to make async calls sync:在 Meteor 中,您使用wrapAsync使异步调用同步:

const putObjectSync = Meteor.wrapAsync(s3Bucket.putObject);

Meteor.methods({
  uploadImage: function (params) {
  
    var AWS = Npm.require('aws-sdk');
    
    AWS.config.loadFromPath(process.env["PWD"]+'/private/awss3/s3_config.json');
    var s3Bucket = new AWS.S3( { params: {Bucket: 'users-profile-pictures'} } );
    
    buf = Buffer.from(params.baseimage.replace(/^data:image\/\w+;base64,/, ""),'base64')
    var data = {
      Key: params.fileName, 
      Body: buf,
      ContentEncoding: 'base64',
      ContentType: 'image/jpeg'
    };
    
    const result = putObjectSync(data); 
    // Note that errors will throw an exception, which is what you want, as
    // they are handled by Meteor, letting the method called know that something
    // went wrong.

    return result;
  },
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM