Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  155] [ 7]  / answers: 1 / hits: 31031  / 10 Years ago, sat, march 15, 2014, 12:00:00

Is it possible to check if by a given url the image exists and it's an image resource ?



for example:



angular.isImage('http://asd.com/asd/asd.jpg')


Or it's just a stuff for the server side ?



NO JQUERY please i'm not using it


More From » angularjs

 Answers
3

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


Usage:



isImage('http://asd.com/asd/asd.jpg').then(function(test) {
console.log(test);
});


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.



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


Demo: http://plnkr.co/edit/u5F6FfO3dEkNSMYV1amo?p=preview


[#71979] Thursday, March 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ignacio

Total Points: 467
Total Questions: 128
Total Answers: 79

Location: Luxembourg
Member since Tue, Mar 14, 2023
1 Year ago
ignacio questions
;