NodeJS 从AWS Lambda上传图像到S3存储桶

nc1teljy  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(89)

我在node.js lambda中尝试了这段代码,它工作了,它将我的图片插入到我的s3桶中,但是当我试图打开s3桶中的图片时,它不会渲染,有人知道为什么吗?我希望可以访问图片URL
enter image description here

const AWS = require('aws-sdk');
const S3 = new AWS.S3();

exports.handler = async (event) => {
  try {
    
    // Extract picture data from the event (e.g., base64 encoded data)
    const pictureData = event.pictureData;

    // Specify the S3 bucket and object key
    const bucketName = 'BUCKET NAME';
    const objectKey = 'lambda/your-object-key3.jpg'; // Adjust the file extension accordingly

    // Convert the picture data to a buffer
    const buffer = Buffer.from(pictureData, 'base64');

    // Upload the picture to S3
    await S3.putObject({
      Bucket: bucketName,
      Key: objectKey,
      Body: buffer,
      ACL: 'public-read', // Optionally set ACL for the uploaded object
      ContentType: 'image/jpeg',
    }).promise();

    return {
      statusCode: 200,
      body: JSON.stringify('Picture uploaded successfully'),
    };
  } catch (err) {
    console.error('Error uploading picture:', err);
    return {
      statusCode: 500,
      body: JSON.stringify('Error uploading picture'),
    };
  }
};

字符串

sf6xfgos

sf6xfgos1#

尝试使用upload方法

await S3.upload({
  Bucket: bucketName,
  Key: objectKey,
  Body: buffer,
  ACL: 'public-read', // Optionally set ACL for the uploaded object
  ContentType: 'image/jpeg',
}).promise();

字符串
您也可以尝试通过Form Data传递图像,而不是在请求正文中使用base64格式。

相关问题