利用JS判断图片,文件是否存在的几种方法

有时候,我们读取一个图片或文件的时候,我们不知道图片和文件是否存在。所以可以事先判断一下图片和文件在服务器上是否存在。

方法1:判断图片是否存在。

function isHasImg(pathImg){
    var ImgObj=new Image();
    ImgObj.src= pathImg;
     if(ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0))
     {
       return true;
     } else {
       return false;
    }
}

方法2:AJAX验证图片链接是否存在

function validateImage(url)
    {    
        var xmlHttp ;
        if (window.ActiveXObject)
         {
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         else if (window.XMLHttpRequest)
         {
          xmlHttp = new XMLHttpRequest();
         } 
        xmlHttp.open("Get",url,false);
        xmlHttp.send();
        if(xmlHttp.status==404)
        return false;
        else
        return true;
    }
方法3:用onerror替换不存在的图片




你可能感兴趣的:(JavaScript)