【问题标题】:How to properly save image to s3 with nodejs that can be displayed?如何使用可以显示的nodejs将图像正确保存到s3?
【发布时间】:2020-10-16 13:17:25
【问题描述】:

我正在将图像从 url 保存到 s3 存储桶。图像已保存,但是当打开该图像的对象 url 时,除了一个小方块外,它没有正确显示图像。图像大小也不为零。我知道有问题,但不确定它在哪里以及如何解决它。任何建议都会很棒。

这是我的代码:

const AWS = require('aws-sdk');
const axios = require('axios');

AWS.config.update({
  accessKeyId: 'xxxxxx',
  secretAccessKey: 'xxx',
});

const S3 = new AWS.S3();

const url = '//../path-to-image';

async function uploadToS3(uri, cb) {
  const image = await axios.get(uri);
  const finalImage = await new Buffer.from(image.data);
  S3.putObject(
    {
      Bucket: 'my-images',
      Key: Date.now() + '.jpg',
      ACL: 'public-read',
      ContentType: 'image/jpeg',
      Body: finalImage,
    },
    function (err) {
      if (err) {
        console.error('Image upload to s3 failed: ', err);
      }
      console.log('Upload to s3 successfull');
    }
  );
}

const handleError = (err, d) => {
  if (err) return new Error(err.stack);
  else console.log('Operation successfull', d);
};

uploadToS3(url, handleError);


【问题讨论】:

  • 如果您在 aws 网站上查看您的对象存储实例,您还能看到图像吗?不知道是上传图片还是显示问题。
  • 我可以点击 aws 图片链接。它在新选项卡中打开。但是新页面中只有一个黑色的小方块(背景)。所以,从这个角度来看,我假设我无法看到图像。
  • 你试过这个问题吗? stackoverflow.com/questions/49604270/…
  • 您可能需要在 axios 中设置响应类型:stackoverflow.com/a/44058739/7933478
  • 试过在 axios 中都使用响应类型,还是同样的问题。打算尝试其他调整。

标签: javascript node.js amazon-s3


【解决方案1】:

虽然我是用 Angular 写的,但基本概念是一样的。

  init() {
    let tawcon:TVAwsConfig = new TVAwsConfig(); // make your own config file
    this.awsconfig = tawcon.aswcon;
    this.bucketName = this.awsconfig.bucketName;

    AWS.config.region = this.awsconfig.bucketRegion;
    AWS.config.apiVersions = {
      s3:this.awsconfig.apiVersions
    }
    this.s3Object =  new AWS.S3();
  }

  public publishPageToS3(params:any,
    loader:LoaderService,
    callBkFunc:Function):void{
    let {foldername, compref, filename, body} = params;
    loader.showLoader = true;
    var objectParams = {
      Bucket: this.bucketName,
      Key: foldername+'/'+compref+'/'+filename,  // write your own folder structure.
      Body: body
    };


    this.s3Object.upload (objectParams, function (err, data) {
      if (err) {
        loader.showLoader = false;
        callBkFunc(err, true)
        return;
      }

      if (data) {
        loader.showLoader = false;
        callBkFunc("Success", false);
      }
     });
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2015-05-16
    相关资源
    最近更新 更多