Javascript Image Url Verify

后端 未结 4 1505
温柔的废话
温柔的废话 2020-11-27 02:49

I need to verify an image url to check whether the url is an image of any of these extensions:- jpeg, jpg, gif, png. Example:- when we verify this url http://www.example.com

相关标签:
4条回答
  • 2020-11-27 02:55

    You can use a regular expression like this to check the file extension:

    function checkURL(url) {
        return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
    }
    

    This checks to see if the url ends in any of those four extensions.

    I know of no way from javascript in the client to verify the content-type of a URL that isn't on the same domain as the web page because you can't use ajax outside of the domain of the web page. As best I know, you'd have to ship the URL to a server process and have it download the image, get the content type and return that to you.

    But, you can check to see if an image tag can load the URL by using a function like this:

    function testImage(url, callback, timeout) {
        timeout = timeout || 5000;
        var timedOut = false, timer;
        var img = new Image();
        img.onerror = img.onabort = function() {
            if (!timedOut) {
                clearTimeout(timer);
                callback(url, "error");
            }
        };
        img.onload = function() {
            if (!timedOut) {
                clearTimeout(timer);
                callback(url, "success");
            }
        };
        img.src = url;
        timer = setTimeout(function() {
            timedOut = true;
            // reset .src to invalid URL so it stops previous
            // loading, but doesn't trigger new load
            img.src = "//!!!!/test.jpg";
            callback(url, "timeout");
        }, timeout); 
    }
    

    This function will call your callback at some future time with two arguments: the original URL and a result ("success", "error" or "timeout"). You can see this work on several URLs, some good and some bad, here: http://jsfiddle.net/jfriend00/qKtra/


    And, since this is now the era of Promises, here's a version that returns a promise:

    function testImage(url, timeoutT) {
        return new Promise(function (resolve, reject) {
            var timeout = timeoutT || 5000;
            var timer, img = new Image();
            img.onerror = img.onabort = function () {
                clearTimeout(timer);
                reject("error");
            };
            img.onload = function () {
                clearTimeout(timer);
                resolve("success");
            };
            timer = setTimeout(function () {
                // reset .src to invalid URL so it stops previous
                // loading, but doesn't trigger new load
                img.src = "//!!!!/test.jpg";
                reject("timeout");
            }, timeout);
            img.src = url;
        });
    }
    

    And, a jsFiddle demo: http://jsfiddle.net/jfriend00/vhtzghkd/

    0 讨论(0)
  • 2020-11-27 02:58

    use the HEAD http request method to check the contenttype...

    $.ajax({
      type: "HEAD",
      url : "urlValue",
      success: function(message,text,response){
         if(response.getResponseHeader('Content-Type').indexOf("image")!=-1){
               alert("image");
        }
      } 
    });
    

    to check whether the string contains that extenstions you can use the inArray method,

    function checkUrl(url){
       var arr = [ "jpeg", "jpg", "gif", "png" ];
       var ext = url.substring(url.lastIndexOf(".")+1);
       if($.inArray(ext,arr)){
         alert("valid url");
         return true;
      }
    }
    

    edit: updated typo

    0 讨论(0)
  • 2020-11-27 03:15

    If you want to check that the string starts with http you can use

    url.match(/^http.*\.(jpeg|jpg|gif|png)$/) != null
    
    0 讨论(0)
  • 2020-11-27 03:22
    let url = "folder/myImage.png";
    if ( isValidImageURL(url) ){
        // do something if url is valid image url.
    }
    
    function isValidImageURL(str){
        if ( typeof str !== 'string' ) return false;
        return !!str.match(/\w+\.(jpg|jpeg|gif|png|tiff|bmp)$/gi);
    }
    
    0 讨论(0)
提交回复
热议问题