【问题标题】:AWS S3 upload file synchronouslyAWS S3 同步上传文件
【发布时间】:2021-05-11 10:07:11
【问题描述】:

我在服务器端使用 Meteor,我使用方法调用返回数据。

所以我正在尝试将文件同步上传到 AWS S3 存储桶。

这是一个示例代码:

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;
    },
});

现在我想返回从 AWS 开发工具包回调中获得的响应。如何同步上传?

【问题讨论】:

标签: node.js amazon-web-services amazon-s3 meteor async-await


【解决方案1】:

在 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;
  },
});

【讨论】:

  • 不工作会报错:this.makeRequest 不是函数
  • this.makeRequest 未出现在此代码中。你确定它没有扔到别的地方吗?
  • @Christain 我至少在我的代码中使用了 this.makeRequest
【解决方案2】:

我不是 AWS SDK 专家,但根据我的经验,所有互联网请求都是异步的,因为服务器需要时间来响应。无论如何,您需要像当前使用的那样使用它,或者您需要将所有脚本异步执行,然后添加 await 标记以等待函数输出:await s3Bucket.putObject(...

【讨论】:

  • 我已经使用了 await 但它给出了语法错误意外标记
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 2019-11-07
  • 2018-07-03
  • 2015-10-10
  • 2020-05-01
相关资源
最近更新 更多