【问题标题】:Meteor - Access and Display ImagesMeteor - 访问和显示图像
【发布时间】:2015-09-07 05:06:25
【问题描述】:

您将如何访问一个充满图像的文件夹,获取每个图像的 url 并将其放入一个数组中,然后在该数组上 {{each}} 以在我选择的页面上显示每个图像?每个人都在说 CollectionFS,但出于某种原因,当我设置它时:

var imageStore = new FS.Store.FileSystem('images', {
    path: '~/category/engagements'
});

Images = new FS.Collection('images', {
    stores: [imageStore]
});

我可以在控制台中访问图像,但数组是空的。这不就是我需要做的吗?

【问题讨论】:

    标签: javascript meteor collectionfs


    【解决方案1】:

    CollectionFS 保留一个 mongo 集合,该集合本质上指向已存储在某个文件系统中某处的图像,无论是在服务器的磁盘上还是在云中。 afaik,您不能简单地将 CollectionFS 指向一个充满文件的目录,您需要首先使用 CollectionFS 将文件放在那里(在您的情况下)Images.insert()

    【讨论】:

      【解决方案2】:

      我发现你的问题很有趣,所以我开始想办法。我对 Meteor 和 Node.js 还很陌生,所以我想有更好理解的人可以提出更好的解决方案,但我的基本想法是将每个图像从目录导入到 CollectionFS。

      这是我想出的(注意,这是一个 10 分钟的模型,而不是复制粘贴解决方案!

      var basedir = '../../../../../public/';
      
      var imageStore = new FS.Store.FileSystem("images", {
        path: basedir
      });
      
      Images = new FS.Collection("images", {
        stores: [imageStore]
      });
      
      
      if (Meteor.isServer) {
      
        Images.allow({
          'insert': function () {
            return true;
          },
          'download' : function(){
            return true;
          }
        });  
      
        function importFiles(importDir) {
          var dir = basedir + importDir;
          var files = fs.readdirSync(dir);
          _(files).each(function(f){
            fs.readFile(dir + f, Meteor.bindEnvironment(function (err, data) {
              if (err) throw err;
      
              var newFile = new FS.File();
      
              newFile.attachData(data, {type: 'image/png'});
              newFile.name(f);
              var insertedFile = Images.insert(newFile,function(err,fob){
                if (err) throw err;
                console.log('Uploaded successfully');
              });
            }));
          })
        }
      
       importFiles('import/'); // this dir in under my public folder
      
      }
      

      此代码将 public/import 中的所有内容导入为imageStore 指定的目录。 不过要小心,这可能会导致严重的内存问题,因为它正在使用 fs.readFile 读取整个文件

      需要安装Node.js fs库meteor add peerlibrary:fs

      不要忘记过滤文件列表并根据扩展名设置正确的 MIME 类型。

      导入图片后,可以使用 CollectionFS find()`` to list the images and thenfileObject.url()```来显示它们。

      CollectionFS GitHub 页面上有示例,例如: https://github.com/CollectionFS/Meteor-CollectionFS/#url

      【讨论】:

        猜你喜欢
        • 2016-01-11
        • 1970-01-01
        • 1970-01-01
        • 2016-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-23
        相关资源
        最近更新 更多