[英]Meteor - How to check if an image exists (server-side)
我的目标:如果不存在默认图像,请显示默认图像。
我的方法:我创建了一个帮助程序,该帮助程序进行服务器端Meteor.call来检查图像URL是否存在。 帮助程序的意图是返回默认图像路径(不存在)或动态路径(图像存在)。
我被困在哪里
助手:在客户端上,我可以成功地console.log服务器端方法(result.statusCode)的输出。 但是,帮助程序不会在模板(/images/db/...etc)中返回我想要的字符串。
方法:我得到所有文件路径的200个结果状态,即使不存在。 我怀疑这与Iron-router的全局NotFound模板有关,但不确定如何解决它。 我尝试使用fs.exists,但无法找到文件(所有响应均为假)。
任何和所有建议,不胜感激。 如果有更简单的方法可以做到这一点,我全都听着。
HTML:
<img src="{{imagePath key}}avatar.jpg">
我的助手:
UI.registerHelper('imagePath', function(key){
//Build the Meteor.call url
var $host = document.location.host;
var $imgBaseUrl = '/images/db/'
var $assetPath = $imgBaseUrl + key + '/';
var url = 'http://' + $host + $assetPath + 'bg.jpg';
//Define the default image location
var $assetPathDefault = $imgBaseUrl + 'default' + '/';
//Call the server-side method
Meteor.call('checkIfImageExists', url, function(error, result) {
if (false) {
console.log('Error');
return $assetPathDefault;
} else {
console.log('Result: ' + result.statusCode);
console.log($assetPath);
return $assetPath;
};
});
});
服务器端方法
Future = Npm.require('fibers/future');
Meteor.methods({
checkIfImageExists: function(url) {
check(url, String);
var fut = new Future();
this.unblock();
HTTP.get(url, function (error, result) {
if (!error) {
console.log('Found a file!: ' + url);
console.log('Result: ' + result.statusCode);
fut.return (result);
} else {
console.log(error);
console.log('Error: ' + error);
fut.return (false);
};
});
return fut.wait();
}
});
FWIW-我将“ URL检查”添加到一个旧的帮助程序中,该帮助程序只是插入了一个不带检查图像是否存在的字符串。 很棒。
UI.registerHelper('imagePath', function(key){
var baseUrl = '/images/db/';
return baseUrl + key + '/';
});
您的客户端助手没有任何回报! 查看您使用过的结构:
function a() {
...
Meteor.call(..., function b() {
return something;
});
}
return something
是函数b
的return语句,而函数a
没有return语句–因此它返回未定义的值。
流星服务器端方法是(而且必须是)异步的,而客户端Javascript的性质意味着助手方法是同步的(浏览器中没有“等待”)。 因此,要在客户端助手中使用服务器端方法,您必须利用反应性。 幸运的是,使用ReactiveDict
非常简单:
var imagePathDict = new ReactiveDict();
UI.registerHelper('imagePath', function(key) {
...
if(!imagePathDict.get(key)) {
// the path was not initialized, fetch it from the server
Meteor.call(..., function(error, result) {
...
imagePathDict.set(key, result.assetPath);
});
}
// return the reactive path
return imagePathDict.get(key);
});
顺便说一句,不要以$
开头变量名(除非您引用jQuery对象),这违反了Javascript中的约定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.