Javascript 显示从 s3 获取的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32702431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:07:23  来源:igfitidea点击:

display images fetched from s3

javascriptangularjsamazon-s3filereaderaws-sdk

提问by Gaurav Gupta

I want to fetch images from s3 and display them on my HTML page.

我想从 s3 获取图像并将它们显示在我的 HTML 页面上。

Angular HTML file:

角度 HTML 文件:

<section data-ng-controller="myCtrl">
    <img ng-src="{{src}}" width="200px" height="200px">
</section>

Angular Controller file:

角度控制器文件:

angular.module('users').controller('myCtrl', ['$scope',function($scope) {
    var s3 = new AWS.S3(); 
    s3.getObject({Bucket: 'mybucket', Key: 'myimage.jpg'},function(err,file){

    //code?? to display this image file in the img tag
    //$scope.src=file????....obviously it wont work

    });
}]);

I found something call FileReaderand tried this one:

我找到了一个叫做FileReader 的东西并尝试了这个:

var reader = new FileReader();
reader.onload = function(event) {
    $scope.src = event.target.result;
}
reader.readAsDataURL(file);

But it shows error:
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

Please help me with the code to display image file in the img tag
My S3 bucket is not public

但它显示错误:
未捕获的类型错误:无法在“FileReader”上执行“readAsDataURL”:参数 1 的类型不是“Blob”。

请帮助我在 img 标签中显示图像文件的代码
我的 S3 存储桶不是公开的

EDIT:
I am not interested in s3. what i want to know is that
how to display an image which you have in your javascript code in the form of a file object(s3 obj) using the HTML image tag

编辑:
我对 s3 不感兴趣。我想知道的是
如何使用 HTML 图像标签以文件对象(s3 obj)的形式显示您在 javascript 代码中拥有的图像

回答by show-me-the-code

You don't "fetch" the images to display. You just point the image URL to the location where they are stored (S3 in your case). So instead of pulling individual object, pull the list of files in that bucket (bucket.listObjects) and then add them to the source of the thumbnails/images.

您不会“获取”要显示的图像。您只需将图像 URL 指向存储它们的位置(在您的情况下为 S3)。因此,bucket.listObjects与其提取单个对象,不如提取该存储桶 ( )中的文件列表,然后将它们添加到缩略图/图像的源中。

<section data-ng-controller="myCtrl">
    <img ng-src="{{s3Url}}{{image.Key}}" width="200px" height="200px" ng-repeat="image in allImageData">
</section>
$scope.s3Url = 'https://s3-<region>.amazonaws.com/myBucket/';
var bucket = new AWS.S3({params: {Bucket: 'myBucket'}});
  bucket.listObjects(function (err, data) {
    if (err) {
      console.log(err);
    } else {
      console.log(data);
      $scope.allImageData = data.Contents;
    }
  });

Assuming here that the files have read permission. They won't be accessible without public read permission for obvious reasons.

假设这里的文件有读权限。出于显而易见的原因,如果没有公共阅读许可,它们将无法访问。

EDIT:Based on the comment, the question is seeking to load the actual image on the page. Here's how to do it:

编辑:根据评论,问题是寻求在页面上加载实际图像。这是如何做到的:

function myCtrl($scope, $timeout) {    
    AWS.config.update({
  accessKeyId: 'YOUR_ACCESS_TOKEN', secretAccessKey: 'YOUR_SECRET'});
    AWS.config.region = "YOUR_REGION";

var bucket = new AWS.S3({params: {Bucket: 'YOUR_BUCKET'}});

    bucket.getObject({Key: 'happy-face.jpg'},function(err,file){

    $timeout(function(){
        $scope.s3url = "data:image/jpeg;base64," + encode(file.Body);
    },1);
});
}

function encode(data)
{
    var str = data.reduce(function(a,b){ return a+String.fromCharCode(b) },'');
    return btoa(str).replace(/.{76}(?=.)/g,'$&\n');
}

The data you get from the S3 is byte array. You need to convert it into the base64encoded data URI. The encode function is borrowed from here. Here's one working jsFiddlewith credentials removed.

您从 S3 获得的数据是字节数组。您需要将其转换为 base64 编码的数据 URI。编码功能是从这里借用的。这是一个已删除凭据的有效jsFiddle

回答by Liad Livnat

Full implementation of getting an image from s3 with promise - enjoy!

完全实现从 s3 获取图像的承诺 - 享受!

<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://sdk.amazonaws.com/js/aws-sdk-2.179.0.min.js"></script>
</head>
<body>
  <img height="200" width="200">
  <script>

    var mimes = {
        'jpeg': 'data:image/jpeg;base64,'
    };

      AWS.config.update({
          signatureVersion: 'v4',
          region: 'us-east-1',
          accessKeyId: '',
          secretAccessKey: ''
      });

      var bucket = new AWS.S3({params: {Bucket: 'xxx'}});

      function encode(data)
      {
          var str = data.reduce(function(a,b){ return a+String.fromCharCode(b) },'');
          return btoa(str).replace(/.{76}(?=.)/g,'$&\n');
      }

      function getUrlByFileName(fileName,mimeType) {
          return new Promise(
              function (resolve, reject) {
                  bucket.getObject({Key: fileName}, function (err, file) {
                      var result =  mimeType + encode(file.Body);
                      resolve(result)
                  });
              }
          );
      }

      function openInNewTab(url) {
          var redirectWindow = window.open(url, '_blank');
          redirectWindow.location;
      }

      getUrlByFileName('sprites.png', mimes.jpeg).then(function(data) {
          //openInNewTab(data);
          document.querySelector('img').src = data;
      });

  </script>
</body>
</html>

回答by michelem

If your S3 file is public (you have to change it, by default it isn't public) you can get the url from this schema:

如果您的 S3 文件是公开的(您必须更改它,默认情况下它不是公开的),您可以从此架构中获取 url:

https://s3-<region>.amazonaws.com/<bucket-name>/<key>

So if the region is eu-west-1with something like this:

因此,如果该地区是eu-west-1,则是这样的:

$scope.src = 'https://s3-eu-west-1.amazonaws.com/mybucket/myimage.jpg';

回答by Siddhu

You only have to mention the url of the image that is stored in the s3.

您只需要提及存储在 s3 中的图像的 url。

https://mybucket.s3.amazonaws.com/myimage.jpg

This should work.

这应该有效。