【问题标题】:Displaying images from private subdirectory in Meteor在 Meteor 中显示来自私有子目录的图像
【发布时间】:2015-10-06 19:21:21
【问题描述】:

我有一组图像存储在我的/private 子目录中,我正在尝试在服务器方法中检索数据并将数据发送回客户端以进行显示。

我该怎么做?


我在/private/photos 中有一个名为test.png 的图像。这是我尝试过的。

/client/test.js

Template.test.onRendered(function () {
    Meteor.call('returnPhoto', 'photos/test.png', function (e, data) {
        console.log(data);
        console.log(window.btoa(data));
        $('#imgContainerImg').attr('src', 'data:image/png;base64,' + window.btoa(data));
    });
})

/server/methods.js

returnPhoto: function (assetPath) {
  return Assets.getText(assetPath);
  return Assets.getBinary(assetPath);
}

我尝试了Assets.getTextAssets.getBinary,第一个给了我一些二进制乱码,第二个给了我一个数字数组。无论如何使用btoa 函数都不起作用。


我查看了CollectionFS 包,但我不需要上传图片并将它们全部存储在一个集合中。我希望将图像放入该目录后立即可用,而无需致电myFSCollection.insert

【问题讨论】:

    标签: javascript image meteor binary


    【解决方案1】:

    使用以下内容,我能够从私有目录中获取图像,将其作为字节数组发送到客户端,然后将其转换为 base64 字符串并显示为数据 URL。

    client/test.js

    Template.test.onRendered(function () {
        Meteor.call('returnPhoto', 'photos/test.png', function (e, data) {
            var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(data)));
            $('#imgContainerImg').attr('src', 'data:image/png;base64,' + base64String);
        });
    })
    

    服务器/methods.js

    returnPhoto: function (assetPath) {
        return Assets.getBinary(assetPath);
    }
    

    【讨论】:

      【解决方案2】:

      这是我使用的解决方案:

      client/main.js

      const imagesLookup = new ReactiveDict();
      Template.registerHelper('img', function(src) {
        Meteor.call('image', src, (err, img)=> {
          imagesLookup.set(src, img);
        });
        return imagesLookup.get(src);
      });
      

      client/main.html

      <template="stuffWithImage">
        <!-- src is the path of the image in private -->
        <img src="{{img src}}"/>
      </template>
      

      imports/methods.js

      Meteor.methods({
        image(src){
          //validate input and check if use is allowed to see this asset
          if(Meteor.isClient){
            //return some loading animation
          }
          const buffer = new Buffer(Assets.getBinary(src), 'binary');
          const magicNumber = buffer.toString('hex',0,4)
          const base64String = buffer.toString('base64');
          return `data:image/${getImageType(magicNumber)};base64,${base64String}`;
        }
      });
      
      function getImageType(magicNumber){
        if (magicNumber === 'ffd8ffe0') {
          return 'jpeg';
        }
        //check for other formats... here is a table: https://asecuritysite.com/forensics/magic
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-05
        • 1970-01-01
        • 2012-09-18
        • 1970-01-01
        • 1970-01-01
        • 2023-01-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多