2010-08-01 15 views
64

Quiero verificar si existe una imagen usando jquery.¿Cómo comprobar si existe una imagen con una URL determinada?

Por ejemplo ¿cómo puedo comprobar esta imagen existe

http://www.google.com/images/srpr/nav_logo14.png 

el cheque me tiene que dar un 200 o bien el estado

-------------- edited- ------------------

var imgsrc = $(this).attr('src'); 
var imgcheck = imgsrc.width; 


if (imgcheck==0) { 
alert("You have a zero size image"); 
} else { //do rest of code } 

Gracias Jean

+1

Tiene todo el derecho de publicar y aceptar una respuesta a su propia pregunta. – sje397

+1

@ sje397 ¡Qué! ... – X10nD

+2

Es cierto. Verifique las preguntas frecuentes. – sje397

Respuesta

73

uso del error controlador de la siguiente manera:

$('#image_id').error(function() { 
    alert('Image does not exist !!'); 
}); 

Si la imagen no puede ser cargado (por ejemplo, debido a que no está presente en la URL suministrado), se muestra la alerta:

Actualización:

Creo que usando:

$.ajax({url:'somefile.dat',type:'HEAD',error:do_something}); 

sería suficiente para comprobar si hay una

404.

Más Lecturas:

Actualizar 2:

El código debería ser así:

$(this).error(function() { 
    alert('Image does not exist !!'); 
}); 

No hay necesidad de estas líneas y que no comprobará si el archivo remoto existe de todos modos:

var imgcheck = imgsrc.width;  

if (imgcheck==0) { 
    alert("You have a zero size image"); 
} else { 
    //execute the rest of code here 
} 
+0

@sAc No tengo una identificación para las imágenes, solo quiero verificar si el archivo está presente, de lo contrario, avance para ejecutar el código restante – X10nD

+0

@Jean: publique su código en su pregunta para ver lo que tiene o cómo necesita esto . – Sarfraz

+0

Si echa un vistazo a esta URL http://www.google.com/images/srpr/nav_logo14.png, si la imagen está presente, debe darme el tamaño, o una pregunta de estado 200/ok – X10nD

2

De here:

// when the DOM is ready 
$(function() { 
    var img = new Image(); 
    // wrap our new image in jQuery, then: 
    $(img) 
    // once the image has loaded, execute this code 
    .load(function() { 
     // set the image hidden by default  
     $(this).hide(); 
     // with the holding div #loader, apply: 
     $('#loader') 
     // remove the loading class (so no background spinner), 
     .removeClass('loading') 
     // then insert our image 
     .append(this); 
     // fade our image in to create a nice effect 
     $(this).fadeIn(); 
    }) 
    // if there was an error loading the image, react accordingly 
    .error(function() { 
     // notify the user that the image could not be loaded 
    }) 
    // *finally*, set the src attribute of the new image to our image 
    .attr('src', 'images/headshot.jpg'); 
}); 
+1

pregunta editada ................ – X10nD

9

si la carga de imágenes por defecto no lo existe o manejar el error

$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) { 
    if (status == "error") 
     $(this).attr('src', 'images/DEFAULT.JPG'); 
    else 
     $(this).attr('src', imgurl); 
    }); 
27
$.ajax({ 
    url:'http://www.example.com/somefile.ext', 
    type:'HEAD', 
    error: function(){ 
      //do something depressing 
    }, 
    success: function(){ 
      //do something cheerful :) 
    } 
}); 

de: http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06

+11

ADVERTENCIA: Aparecerá un error: [XMLHttpRequest no puede cargar http://not.on.your.domain.com/someimg.jpg. No hay un encabezado 'Access-Control-Allow-Origin' en el recurso solicitado.] Así que esta es solo una buena opción si la imagen está en su servidor. – Twelve24

4

caso de uso

$('#myImg').safeUrl({wanted:"http://example/nature.png",rm:"/myproject/images/anonym.png"}); 

API:

$.fn.safeUrl=function(args){ 
    var that=this; 
    if($(that).attr('data-safeurl') && $(that).attr('data-safeurl') === 'found'){ 
     return that; 
    }else{ 
     $.ajax({ 
    url:args.wanted, 
    type:'HEAD', 
    error: 
     function(){ 
      $(that).attr('src',args.rm) 
     }, 
    success: 
     function(){ 
      $(that).attr('src',args.wanted) 
      $(that).attr('data-safeurl','found'); 
     } 
     }); 
    } 


return that; 
}; 

Nota: rm significa aquí gerencia de riesgos.


Otro caso de uso:

$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"}) 
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"}); 
  • 'http://example/1.png': si no existe 'http://example/2.png'

  • 'http://example/2.png': si no existe 'http://example/3.png'

Cuestiones relacionadas