Meteor中 用collectionFS上傳圖片並顯示到介面上,meteorcollectionfs
用collectionFS上傳圖片並顯示到介面上關鍵是要,確定是否完全上傳完成,再通過Session通知介面顯示 。方法 有兩種:1,用fileObj.hasStored(‘你的資料庫表名’) 2. file.isUploaded()
本文用第一種方法。
原文:http://blog.csdn.net/casun_li/article/details/46356379
1. 伺服器端
//表徵圖檔案images = new FS.Collection("imges",{ stores: [new FS.Store.FileSystem("imges", {path:"/data/files/images"})], filter: { maxSize: 100*1024*1024, // in bytes allow: { extensions: ['png'] }, onInvalid: function (message) { if (Meteor.isClient) { alert(message); } else { console.log(message); } } }});2. client: var setIconUploaded=function(fileObj){ var intervalHandle = Meteor.setInterval(function () { //console.log("intervalHandle。。。。。。。。。"); if (fileObj.hasStored(‘你的資料庫表名’)) {//等檔案儲存體成功後再調用 //這具方法有一個問題,一定要有 //images.findOne(fileObj._id)查到資料出來,fileObj.hasStored()才起作用
Session.set('iconUploaded', true);
//console.log("Session.set('iconUploaded', true)");
// file has stored, close out interval
Meteor.clearInterval(intervalHandle);
}else{
//console.log("intervalHandle。。。1000。");
}
},
1000);}
Template.uploadimg.events({ 'change #img': function(event, template) {//表徵圖
FS.Utility.eachFile(event, function(file) { images.insert(file, function (err, fileObj) { if (err) { //alert('上傳表徵圖失敗:'+err); console.log('上傳表徵圖失敗:'+err); return; } Session.set('iconUploaded', false); console.log("上傳表徵圖成功"); setIconUploaded(fileObj);//通過這個方法通知介面顯示 }); }); }});
Template.uploadimg.helpers({ showIcon:function(){ console.log("Session.get('iconUploaded')"+Session.get('iconUploaded')); if(Session.get('iconUploaded')){ return 'cfs/files/imges/'+icon_file_id;//icon_file_id: 一個變數,fileObj._id 的値給他; } return "";//Session.get("icon_file_id","") }});
3.html:
<div class="form-group"> <div class="col-sm-10"> <input type="file" id="img" > <p class="help-block">請上傳512X512像素PNG格式圖片,大小不超過512kB</p> </div></div>
<div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <img src="{{showIcon}}" alt="icon"> </div></div>4.最後的大問題 發再用fileObj.hasStored(‘你的資料庫表名’)方法不起作用 ,原來沒subsribeserver:Meteor.publish("imgges", function () { return imges.find();});client:Template.uploadimg.onRendered(function () { this.autorun(function () { Meteor.subscribe("imgges"); });});
原文:http://blog.csdn.net/casun_li/article/details/46356379
參考:http://stackoverflow.com/questions/29313486/meteor-collectionfs-make-sure-the-image-is-uploaded-before-displaying/29832414#29832414
http://stackoverflow.com/questions/28860545/is-there-any-event-to-indicate-that-the-uploaded-file-has-been-written-with-coll/28860844#28860844