Check if an image exists in the folder

0

We have a web portal in which each user appears with an image.

In a folder we have all the photos of the users. The name of the images is the ID of each user.

We want that if an image does not exist (the image of a user), a standard image appears in the image of that user.

The following code:

function (data, type, row, meta) {                              
    return '<img src="../Fotos/' + data.dni + '.jpg" width="64" height="89"  alt=""/>';
}

What I need is to check if the route exists (src="../Pictures/" + data.dni + ". jpg") and if it does not exist, change the route (this is easy).

What I can not do is check if the route exists (if the image is in the folder).

I tried to do it with an ajax call to a php file but it does not work for me.

Greetings.

    
asked by M. Giner 25.10.2017 в 08:39
source

2 answers

2

You can use the onerror event to load a default image in case the load fails:

function cargarImagenes(){
  var img1 = document.getElementById('imagen1');
  img1.onerror = cargarImagenPorDefecto;
  var img2 = document.getElementById('imagen2');
  img2.onerror = cargarImagenPorDefecto;
}

function cargarImagenPorDefecto(e){
  e.target.src= 'https://www.blackwallst.directory/images/NoImageAvailable.png';
}
cargarImagenes();
img{
  padding: 10px;
  width: 100px;
}
<img src="https://icon-icons.com/icons2/458/PNG/128/Shy-Minion-icon_43752.png" id="imagen1" />
<img src="https://imagen-noexiste.com/noimage.png" id="imagen2" />
    
answered by 25.10.2017 / 08:49
source
0

Depends on the server technology you are using:

- NodeJS: 
const fs = require('fs')
fs.access('ruta del archivo', err => {
 if (err) console.log('El archivo no existe')
})

- Apache u otros servidores corriendo con PHP:
if (file_exists('ruta del archivo')) {} else { echo 'El fichero no existe' }
    
answered by 25.10.2017 в 12:56