无法访问上传的图像 - 流星网格FS

Can't access uploaded images - Meteor GridFS

本文关键字:流星 网格 FS 图像 访问      更新时间:2023-09-26

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

我不确定它们是否已成功上传,但图像和条目图像集合已成功填充信息。

这是我的代码:

// 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;
    }
});

使用此代码,我的图像集合将填充和条目,如我所期望的那样:

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

和粮安委。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"
    }
  }
}

问题是我仍然无法使用保存在数据库中的 url 访问图像(如果存在的话)。

我也尝试了不安全和启用自动发布,但它仍然不起作用。

在服务器端代码中允许对 gridfs 集合执行"下载"操作非常重要:

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

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

虽然我无法让上面的代码按预期运行,但我设法按照本指南运行图像上传:如何使用流星JS上传文件