角JS - isImage() - 检查它是否是通过图像URL [英] Angular js - isImage( ) - check if it's image by url

查看:350
本文介绍了角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
        }
    };
});

这篇关于角JS - isImage() - 检查它是否是通过图像URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆