角JS - isImage() - 检查它是否是通过图像URL
是否有可能通过指定网址的形象存在,检查,它是一个图像资源?
Is it possible to check if by a given url the image exists and it's an image resource ?
例如:
angular.isImage('http://asd.com/asd/asd.jpg')
或者它只是一个服务器端的东西吗?
Or it's just a stuff for the server side ?
没有jQuery,请我不使用它
NO JQUERY please i'm not using it
我认为最好的JavaScript方式是使用HTMLImageElement对象,Deferred对象:
I think the best javascript approach would be to use HTMLImageElement object with deferred object:
function isImage(src) {
var deferred = $q.defer();
var image = new Image();
image.onerror = function() {
deferred.resolve(false);
};
image.onload = function() {
deferred.resolve(true);
};
image.src = src;
return deferred.promise;
}
用法:
isImage('http://asd.com/asd/asd.jpg').then(function(test) {
console.log(test);
});
使用 HTMLImageElement
给你一些好处:它不仅将测试该文件是可下载的,而且它是一个可以通过显示有效的图像资源IMG
标记。
Using HTMLImageElement
gives you some benefits: not only it tests that the file is downloadable but also it is valid image resource that can be displayed by img
tag.
我裹着简单的服务,这code进行测试,它似乎工作:
I wrapped this code in simple service to make a test and it seems to work:
app.controller('MainCtrl', function($scope, Utils) {
$scope.test = function() {
Utils.isImage($scope.source).then(function(result) {
$scope.result = result;
});
};
});
app.factory('Utils', function($q) {
return {
isImage: function(src) {
// ... above code for isImage function
}
};
});