javascript – 无法访问上传的图像 – Meteor GridFS

我试图使用GridFS在Meteor上制作上传图像功能,一切似乎都有效但我无法访问这些文件.

我不确定它们是否已成功上传,但Images和EntriesImages集合已成功填充信息.

这是我的代码:

// 1. Packages
cfs:standard-packages
cfs:gridfs

// --------------------


// 2. Defining the collections + schema (collections folder)
Images = new Mongo.Collection('images');

EntriesImages = new FS.Collection("EntriesImages", {
   stores: [new FS.Store.GridFS('EntriesImages')]
});

ImagesSchema = new SimpleSchema({
    image: {
        type: String,
        label: "Image"
    },
    author: {
        type: String,
        label: "Author",
        autoValue: function(){
            return this.userId
        },
        autoform: {
            type: "hidden"
        }
    }
});
Images.attachSchema(ImagesSchema);

// --------------------

// 3. Publishing the collections (server folder)
Meteor.publish('images', function(){
    return Images.find({author: this.userId});
});
Meteor.publish('EntriesImages', function(){
    return EntriesImages.find();
});
// --------------------


// 4. Subscribe and upload functionality(client folder)
Meteor.subscribe('images');
Meteor.subscribe('EntriesImages');

Template.addImages.helpers({
    images: ()=> {
        return Images.find({});
    }
});

Template.addImages.events({
    'submit .add-images': function(event, template) {
        // get the image from the form
        var file = $('.imageInput').get(0).files[0];

        // check if img was uploaded
        if(file){
            fsFile = new FS.File(file);

            EntriesImages.insert(fsFile, function(err, fileObj){
                // if there is no error we make an insert
                if(!err){
                    var productImage = '/cfs/files/ProductsImages/' + fileObj._id;
                    Images.insert({
                        image: productImage
                    });
                }
            });

        } else {
            console.log('something bad happend');
        }

        return false;
    }
});

使用此代码,我的Images集合将按照我的预期填充和输入:

// sample entry
{
    "_id": "Qp8Hsgki5G9DT2dGz",
    "image": "/cfs/files/ProductsImages/drbbaj7BKzttzzgZX",
    "author": "TMviRL8otm3ZsddSt"
}

并且cfs.EntriesImages.filerecord也会填充一个条目:

{
  "_id": "x4Sei5sbnFwDii4HE",
  "original": {
    "name": "dash.png",
    "updatedAt": "2015-12-15T14:32:10.000Z",
    "size": 542121,
    "type": "image/png"
  },
  "uploadedAt": "2016-01-18T13:08:34.914Z",
  "copies": {
    "EntriesImages": {
      "name": "dash.png",
      "type": "image/png",
      "size": 542121,
      "key": "569ce3d2e28bd3035ba03735",
      "updatedAt": "2016-01-18T13:08:34.937Z",
      "createdAt": "2016-01-18T13:08:34.937Z"
    }
  }
}

问题是我仍然无法使用在db中保存的url访问图像(如果它存在).

我也试过启用不安全和自动发布,但它仍然无法正常工作..

最佳答案 在服务器端代码中对gridfs集合允许“下载”操作非常重要:

EntriesImages.allow({    
  download: function(userId, fileObj) {
     return true
 }
});

没有这个,网址将无法正常工作

点赞