Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

javascript - Angular js - isImage( ) - check if it's image by url

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...