【问题标题】:Insert pictures in Meteor在 Meteor 中插入图片
【发布时间】:2016-12-30 07:47:16
【问题描述】:

我刚开始学习 Meteor。我将所有图像放在“/public”文件夹的根目录中。这些图像被命名为“1.jpg”、“2.jpg”、“3.jpg”.... for 循环限制。那么如何让它自动检测公用文件夹中有多少张图片呢?

【问题讨论】:

  • 那么这些文件是图像的事实是否相关,或者可以直接编辑掉?您的问题似乎只是“如何在 Meteor 中获取文件夹中的文件数量”,而图像与它无关。
  • 是的,我想获取 Meteor 中“public”文件夹中的文件数量。

标签: javascript jquery mongodb meteor


【解决方案1】:

您需要一种机制来获取公用文件夹中的图像列表,使用fs 包将为您完成此操作。考虑以下示例,该示例使用包从服务器读取公共目录 /web.browser/app/(总 unix 路径 /home/user/your_app_name/.meteor/local/build/programs/web.browser/app/)。

获取文件夹列表后,过滤列表以仅获取扩展名为.jpg 的图像文件,然后将图像插入您的收藏。出于说明目的,保存到集合中的图像文档具有以下简单的模式示例

{ _id: "v2PrCTPea6tM6JNHn", name: "1.jpg" }

为了帮助您实现将图像插入 mongo 集合的最终目标,您可以使用 batch-insert Meteor 包,它使基础 mongo 驱动程序能够插入多个文档。它的工作方式与insert() 类似,但需要插入一组对象而不是单个对象。

#安装

在你的流星应用目录中运行:

meteor add mikowals:batch-insert

在服务器上

var fs = Npm.require('fs'),
    public_path = path.join(__meteor_bootstrap__.serverDir, "../web.browser/app"),
    files = fs.readdirSync(public_path),
    images = _(files).reject( function(fileName) {
        return fileName.indexOf('.jpg') < 0;
    }),
    imagesList = images.map(function (image){
        return { name: image };
    });

Images = new Meteor.Collection('images');

Images.allow({
    insert: function(){ return true };
});

var newIds = Images.batchInsert(imagesList);  // returns array of created _id values

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    相关资源
    最近更新 更多