Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if image exists on server using JavaScript?

Tags:

javascript

People also ask

How do you check if an image exists on the server in Javascript?

In modern JavaScript, you can use the Fetch API to check if an image or any other resource file exists on the server. Fetch is a simple promise-based API for asynchronously fetching resources from the server. Here is an example that uses Fetch API to check if an image exists: fetch('/img/bulb.

How check image exist or not in jquery?

Use the error handler like this: $('#image_id'). error(function() { alert('Image does not exist !! '); });


You could use something like:

function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status != 404;

}

Obviously you could use jQuery/similar to perform your HTTP request.

$.get(image_url)
    .done(function() { 
        // Do something now you know the image exists.

    }).fail(function() { 
        // Image doesn't exist - do something else.

    })

You can use the basic way image preloaders work to test if an image exists.

function checkImage(imageSrc, good, bad) {
    var img = new Image();
    img.onload = good; 
    img.onerror = bad;
    img.src = imageSrc;
}

checkImage("foo.gif", function(){ alert("good"); }, function(){ alert("bad"); } );

JSFiddle


You can just check if the image loads or not by using the built in events that is provided for all images.

The onload and onerror events will tell you if the image loaded successfully or if an error occured :

var image = new Image();

image.onload = function() {
    // image exists and is loaded
    document.body.appendChild(image);
}
image.onerror = function() {
    // image did not load

    var err = new Image();
    err.src = '/error.png';

    document.body.appendChild(err);
}

image.src = "../imgs/6.jpg";

A better and modern approach is to use ES6 Fetch API to check if an image exists or not:

fetch('https://via.placeholder.com/150', { method: 'HEAD' })
    .then(res => {
        if (res.ok) {
            console.log('Image exists.');
        } else {
            console.log('Image does not exist.');
        }
    }).catch(err => console.log('Error:', err));

Make sure you are either making the same-origin requests or CORS is enabled on the server.


If anyone comes to this page looking to do this in a React-based client, you can do something like the below, which was an answer original provided by Sophia Alpert of the React team here

getInitialState: function(event) {
    return {image: "http://example.com/primary_image.jpg"};
},
handleError: function(event) {
    this.setState({image: "http://example.com/failover_image.jpg"});
},
render: function() {
    return (
        <img onError={this.handleError} src={src} />;
    );
}

Basicaly a promisified version of @espascarello and @adeneo answers, with a fallback parameter:

const getImageOrFallback = (path, fallback) => {
  return new Promise(resolve => {
    const img = new Image();
    img.src = path;
    img.onload = () => resolve(path);
    img.onerror = () => resolve(fallback);
  });
};

// Usage:

const link = getImageOrFallback(
  'https://www.fillmurray.com/640/360',
  'https://via.placeholder.com/150'
  ).then(result => console.log(result) || result)

Edit march 2021 After a conversation with @hitautodestruct I decided to add a more "canonical" version of the Promise based function. onerror case is now being rejected, but then caught and returning a default value:

function getImageOrFallback(url, fallback) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.src = url
    img.onload = () => resolve(url)
    img.onerror = () => {
      reject(`image not found for url ${url}`)
    }
  }).catch(() => {
    return fallback
  })
}

getImageOrFallback("https://google.com", "https://picsum.photos/400/300").then(validUrl => {
  console.log(validUrl)
  document.body.style.backgroundImage = `url(${validUrl})`
})
html, body {
  height: 100%;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  overflow-y: hidden;
}

Note: I may personally like the fetch solution more, but it has a drawback – if your server is configured in a specific way, it can return 200 / 304, even if the file doesn't exist. This, on the other hand, will do the job.


If you create an image tag and add it to the DOM, either its onload or onerror event should fire. If onerror fires, the image doesn't exist on the server.