簡體   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