流星:显示来自aws s3的图像

时间:2016-01-20 01:59:06

标签: javascript amazon-web-services meteor amazon-s3

在流星应用程序中,从aws s3获取图像的最佳方法是什么?我尝试了三种方法,但都有问题。

方法1:常用解决方案

问题: img标记在http://s3.amazonaws.com/etc...开始之前加载字符串{{copies.original.key}}。这会在图片加载时显示损坏的图片图标。

client.js

Template.newProduct.helpers({

    'image': function(){
        newImages = // logic here; 
        return Images.find({'_id':{'$in':newImages}});
    }
});

template.html

<template name="newProduct">
  {{#each image}}
    <img src="http://s3.amazonaws.com/etc...{{copies.original.key}}">
  {{/each}}    
</template>

方法2:遍历每个图片获取网址并将其投放到数组中以展开{{#each image}}

问题:每当添加图像时,此功能都会再次运行,并且必须重新加载图像。导致长闪烁更新。我只想加载新图像。

client.js

Template.newProduct.helpers({

    'image': function(){
        newImages = // logic here; 
        x = Images.find({'_id':{'$in':newImages}});
        var returnArray = [];
          for(i=0;i<x.count();i++){
            stringResult = "http://s3.amazonaws.com/etc..." + x.fetch()[i].copies.original.key;
            returnArray.push(stringResult);
          }
        return returnArray;
    }
});

template.html

<template name="newProduct">
    {{#each image}}
        <img src="{{this}}">
    {{/each}}
</template>

方法3:在文件上传时,使用js构建图像标记并将其添加到页面中。

问题:以这种方式从其他网站加载图片时会导致403(禁止)错误。你无法动态加载这样的图像。

'change .in': function(ev, t) {
     FS.Utility.eachFile(ev, function(file) {
          Images.insert(file, function (e,f) {
            if (!e){ 
              $('#imageShack').append($('<img />').attr('src', 'http://s3.amazonaws.com/etc..' + f._id + '-' + f.original.name));
            }
          });
     });
}

1 个答案:

答案 0 :(得分:1)

我认为,当你说:

时,你已经完全确定了问题
  

问题:在{{copies.original.key}}开始之前,img标记加载了字符串http://s3.amazonaws.com/etc ....这会在图像加载时显示损坏的图像图标。

避免这种情况的方式是

  1. 要保存完整生成的图片网址,只需在中使用 模板
  2. 通过模板助手生成完整的网址
  3. 这两种解决方案都可以解决您的问题,因为它们以完整且不间断的形式提供网址。

    解决方案1 ​​

    <强> template.html

    <template name="newProduct">
      {{#each image}}
        <img src="{{copies.original.s3Url}}">
      {{/each}}    
    </template>
    

    解决方案2

    <强> template.html

    <template name="newProduct">
      {{#each image}}
        <img src="{{getImageUrl copies.original.key}}">
      {{/each}}    
    </template>
    

    <强> client.js

    Template.newProduct.helpers({
    
        'image': function(){
           newImages = // logic here; 
           return Images.find({'_id':{'$in':newImages}});
        }
    
        'getImageUrl': function(key){
            return 'http://s3.amazonaws.com/etc...' + key;
        }
    });
    

    就个人而言,我赞成解决方案#1。

    当我将图像上传到s3时,我存储了完整的URL(包括存储桶名称),因为这实际上是该图像版本的完整标识。

    图像键只是身份的一部分,如果依赖于部分身份,您几乎总会遇到额外的复杂性。