繁体   English   中英

AWS S3 同步上传文件

[英]AWS S3 upload file synchronously

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

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

这是一个示例代码:

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 SDK 回调得到的响应。 我怎样才能使这个上传同步?

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

在 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