【问题标题】:Display image from s3显示来自 s3 的图像
【发布时间】:2018-08-05 09:09:14
【问题描述】:

我正在尝试显示已上传到 S3 的图像。我相信权限是正确的,因为我可以点击 url 并取回数据。但是,当我将 URL 放入图像标签中时,我得到了一个损坏的链接。

当我将图像标签放在我的网站上的网络选项卡中时,我看到了对 s3 的调用(响应为 200),但正文为空。如果我直接点击 s3 url,我会取回数据并在网络选项卡中看到来自 s3 的带有响应正文的调用。

我正在将图像从 Vue 前端上传到 express/node 后端。我在 s3 中看到图像很好。

s3.putObject({
    Bucket: 'MYBUCKET',
    Key: `${result._id}-${file.upload.filename}`,
    Body: file.dataURL,
    ACL: 'public-read',
    ContentType: 'binary',
    ContentEncoding: 'utf8'
}, function (resp) {});

小提琴:https://jsfiddle.net/Xadvz/7327/

我使用直接点击 s3 返回的数据并显示图像,但是当我输入 s3 url 时,它显示的链接断开。

【问题讨论】:

    标签: html node.js amazon-s3 vue.js


    【解决方案1】:

    你确定Content-Type: 'binary' 是正确的吗?该值与MIME type 相同。以下是一些典型的类型:

    *.jpg ....................................image/jpeg

    *.html ..................................text/html

    *.txt ..................................... text/plain

    *.mp3 ....................................audio/mpeg

    未知/默认 ....................application/octet-stream

    Content-Type 值必须符合与 MIME 类型相同的语法:

    type/sub-type
    

    如果你不确定至少应该使用application/octet-stream

    【讨论】:

    【解决方案2】:

    S3 不支持dataURL 数据格式。

    在您的后端:

    1. 将dataURL转换为buffer
    2. 根据dataURL设置S3对象的ContentType

    代码:

    var regex = /^data:.+\/(.+);base64,(.*)$/;
    
    var matches = file.dataURL.match(regex);
    var ext = matches[1]; // image/jpeg
    var data = matches[2]; // base64 string
    
    var buffer = new Buffer(data, 'base64');
    
    s3.putObject({
        Bucket: 'MYBUCKET',
        Key: `${result._id}-${file.upload.filename}`,
        Body: buffer, // upload binary
        ACL: 'public-read',
        ContentType: ext // set content type
    }, function (resp) {});
    

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 2020-08-10
      • 2021-08-28
      • 2021-11-23
      • 2015-04-26
      相关资源
      最近更新 更多