使用aws-sdk使用nodejs将图像上传到s3

时间:2021-05-06 23:06:25

I want to upload images to amazon web server and for that I am using aws-sdk with nodejs.

我想将图像上传到亚马逊网络服务器,为此我使用带有nodejs的aws-sdk。

I am able to upload images to the s3 bucket, but when I click on the URL to access them I get access-denied error.

我能够将图像上传到s3存储桶,但是当我点击URL访问它们时,我得到访问被拒绝错误。

Here is my configuration

这是我的配置

     var AWS = require('aws-sdk');

     //aws credentials
     AWS.config = new AWS.Config();
     AWS.config.accessKeyId = "<access_key>";
     AWS.config.secretAccessKey = "<secret_key>";
     AWS.config.region = "ap-southeast-1";
     AWS.config.apiVersions = {
        "s3": "2006-03-01"
     }

    var s3 = new AWS.S3();

    var bodystream = fs.createReadStream(req.files.pic.path);

    var params = {
        'Bucket': '<bucket_name>',
        'Key': 'uploads/images/' + req.files.pic.name,
        'Body': bodystream,
        'ContentEncoding': 'base64', 
        'ContentType ': 'image/jpeg'
     };

     //also tried with s3.putObject
     s3.upload(params, function(err, data){
        console.log('after s3 upload====', err, data);
     }) 

Images are uploading successfully but their content-type is application/octet. Also I think that there is some permission issue, because when I add a new permission then I am able to download the image but not able to see it.

图像上传成功但其内容类型为application / octet。另外我认为存在一些权限问题,因为当我添加新权限时,我可以下载图像但无法看到它。

Can you tell me what is wrong with this configuration and also I want to know the difference between s3.upload and s3.putObject method.

你能告诉我这个配置有什么问题吗?我想知道s3.upload和s3.putObject方法之间的区别。

1 个解决方案

#1


3  

In order to specify Content-Type header you need to define Metadata section:

要指定Content-Type标头,您需要定义元数据部分:

var params = {
    'Bucket': '<bucket_name>',
    'Key': 'uploads/images/' + req.files.pic.name,
    'Body': bodystream,
    'ContentEncoding': 'base64', 
    Metadata: {
        'Content-Type': 'image/jpeg'
    }

 };

#1


3  

In order to specify Content-Type header you need to define Metadata section:

要指定Content-Type标头,您需要定义元数据部分:

var params = {
    'Bucket': '<bucket_name>',
    'Key': 'uploads/images/' + req.files.pic.name,
    'Body': bodystream,
    'ContentEncoding': 'base64', 
    Metadata: {
        'Content-Type': 'image/jpeg'
    }

 };