我正在尝试使用 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"
}
}
}
问题是我仍然无法使用保存在数据库中的 url 访问图像(如果它存在的话)。
我也尝试过启用不安全和自动发布,但它仍然无法正常工作..