Check the existence of a file

Asked

Viewed 761 times

0

I need to verify the existence of an image coming in one of the positions of a JSON received via AJAX. Did you understand?

Is there any function equivalent to file_exists() PHP in Javascript or jQuery?

$.ajax({
  url:'http://www.example.com/verificafotos.json',
  success: function(dados) {
   $.each(dados, function(index,value){
    value['titulo'];
    value['imagem'];

    if( SE O ARQUIVO EXISTIR (value['imagem'])) {
      $('img').src(value['imagem']);
    } else {
      $('img').src('http://www.example.com/imagemalternativa.jpg');
    }

   });
  }
});
  • You want to know if some value has something with the image extension, like . png, . jpg etc, or a <img tag>?

  • I import the data from a DB with the image information (fototeste.jpg) and the folder where the photos are. But the image does not always exist in the folder. When mounting the structure, coming from a JSON, does not display the image on the system.

2 answers

0

With Jquery:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //arquiv não existe
    },
    success: function()
    {
        //arquivo existe
    }
});

0

You can check if the image exists through the URL by creating an object new Image() and using events such as onload (the image was loaded) and onerror (the image was not loaded).

The each would look like this:

$.each(dados, function(index,value){
   var tit = value['titulo'],
       img = value['imagem'],
       imgs = new Image();

   imgs.src = img;

   imgs.onload = function(caminho){
      $('img').attr('src', caminho.path[0].src);
   }

   imgs.onerror = function(caminho){
      $('img').attr('src', 'http://www.example.com/imagemalternativa.jpg');
   }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.