簡體   English   中英

使用節點 js 將圖像上傳到 AWS s3 存儲桶時遇到問題

[英]Having trouble uploading image to AWS s3 bucket with node js

我正在嘗試使用 nodejs 和 aws sdk 將圖像上傳到 s3。 它不斷返回一個奇怪的錯誤: “無法訪問的主機:`images.dynamodb.us-east-1.amazonaws.com'。該服務在'us-east-1'地區可能不可用

這是我的 lambda 代碼:

exports.handler = function(event,context,callback){
     var s3 = new AWS.S3();
     const image = event.body.imageBinary;

     var buf = new Buffer.from(image.replace(/^data:image\/\w+;base64,/, ""),'base64');
     const type = image.split(';')[0].split('/')[1];
     var params = {
          Bucket: process.env.BUCKET,
          Key: `${AccountId}.${type}`, 
          Body: buf,
          ContentEncoding: 'base64',
          ContentType: `image/${type}`
      };

      s3.upload(params, function(err, resp){
          if (err) { 
             console.log(err);

          } else {
             console.log('succesfully uploaded the image!: ' + JSON.stringify(resp));

          }
      });
}

我什至嘗試設置 AWS 對象配置(使用密鑰、秘密密鑰和區域)但得到了相同的響應

我的 aws sdk 版本: “aws-sdk”:“^2.610.0”任何幫助都會很好

謝謝!!!

Lambda 支持 node.js v12。 它允許您編寫async/await代碼

const AWS = require('aws-sdk');
const s3 = new AWS.S3({
  region: 'us-east-1',
  apiVersion: '2006-03-01',
});

exports.handler = async(event,context) => {
 const image = event.body.imageBinary;

 const buf = new Buffer.from(image.replace(/^data:image\/\w+;base64,/, ""),'base64');
 const type = image.split(';')[0].split('/')[1];

 var params = {
      Bucket: process.env.BUCKET,
      Key: `${AccountId}.${type}`, 
      Body: buf,
  };

  const options = {
    ACL: 'private',
    CacheControl: 'max-age=86400',
    ContentType: `image/${type}`,
    ContentEncoding: 'base64',
  };

  await s3.upload(params, options).promise();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM