How do I check if file exists in jQuery or pure JavaScript?

How do I check if file exists in jQuery or pure JavaScript?

How do I check if a file on my server exists in jQuery or pure JavaScript?


Solution 1:

With jQuery:

    error: function()
        //file not exists
    success: function()
        //file exists


Here is the code for checking 404 status, without using jQuery

function UrlExists(url)
    var http = new XMLHttpRequest();'HEAD', url, false);
    return http.status!=404;

Small changes and it could check for status HTTP status code 200 (success), instead.

Solution 2:

A similar and more up-to-date approach.

    .done(function() { 
        // exists code 
    }).fail(function() { 
        // not exists code

Solution 3:

This works for me:

function ImageExist(url) 
   var img = new Image();
   img.src = url;
   return img.height != 0;

Solution 4:

i used this script to add alternative image

function imgError()
alert('The image could not be loaded.');


<img src="image.gif" onerror="imgError()" />

Solution 5:

So long as you’re testing files on the same domain this should work:

function fileExists(url) {
        var req = new XMLHttpRequest();'GET', url, false);
        return req.status==200;
    } else {
        return false;

Please note, this example is using a GET request, which besides getting the headers (all you need to check weather the file exists) gets the whole file.
If the file is big enough this method can take a while to complete.

Related:  Remove object from array of objects

The better way to do this would be changing this line:'GET', url, false); to'HEAD', url, false);

Solution 6:

I was getting a cross domain permissions issue when trying to run the answer to this question so I went with:

function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
    return true;
}).bind('error', function() {
    return false;

It seems to work great, hope this helps someone!