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

JavascriptJqueryFile Io

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

With jQuery:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

EDIT:

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

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

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

EDIT 2: Since sync XMLHttpRequest is deprecated, you can add a utility method like this to do it async:

function executeIfFileExist(src, callback) {
    var xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function() {
        if (this.readyState === this.DONE) {
            callback()
        }
    }
    xhr.open('HEAD', src)
}

Solution 2 - Javascript

A similar and more up-to-date approach.

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

Solution 3 - Javascript

This works for me:

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

Solution 4 - Javascript

i used this script to add alternative image

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

HTML:

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

http://wap.w3schools.com/jsref/event_onerror.asp

Solution 5 - Javascript

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

function fileExists(url) {
    if(url){
        var req = new XMLHttpRequest();
        req.open('GET', url, false);
        req.send();
        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.

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

Solution 6 - Javascript

Here's how to do it ES7 way, if you're using Babel transpiler or Typescript 2:

async function isUrlFound(url) {
  try {
    const response = await fetch(url, {
      method: 'HEAD',
      cache: 'no-cache'
    });

    return response.status === 200;

  } catch(error) {
    // console.log(error);
    return false;
  }
}

Then inside your other async scope, you can easily check whether url exist:

const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');

console.log(isValidUrl); // true || false

Solution 7 - Javascript

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!

Solution 8 - Javascript

None of the answers consider the browser's cache!

All of the provided answers would fail when browser makes preceding HTTP request to the file without Cache-Control: no-store header. Then making a XMLHttpRequest to the file on the server is intercepted with the browser's cache and the cached response is returned. But the file may be deleted on the server in the meantime.

Proper solution would be to create non-cached HTTP HEAD request:

const fileExists = file =>
  fetch(file, {method: 'HEAD', cache: 'no-store'})
  .then(response => response.status==200);

fileExists("yourFile.html").then(yes => yes && alert("yourFile.html exists"));

You should also keep in mind that redirection (3xx responses) may occur, so the file can exist elsewhere and may be returned from different location: depending on the use-case, one may choose to follow redirection instead of returning false in this case.

Also keep in mind that background requests will be blocked if you check file existence on different domain and its CORS policy is not opened to your server.

Since we live in the future now, I would also recommend:

  • $.ajax() obsolete, don't use in new projects
  • XMLHttpRequest obsolete, don't use in new projects
  • fetch modern approach, use it if you are free to choose

Solution 9 - Javascript

I use this script to check if a file exists (also it handles the cross origin issue):

$.ajax(url, {
       method: 'GET',
       dataType: 'jsonp'
         })
   .done(function(response) { 
        // exists code 
    }).fail(function(response) { 
        // doesnt exist
    })

Note that the following syntax error is thrown when the file being checked doesn't contain JSON.

> Uncaught SyntaxError: Unexpected token <

Solution 10 - Javascript

For a client computer this can be achieved by:

try
{
  var myObject, f;
  myObject = new ActiveXObject("Scripting.FileSystemObject");
  f =   myObject.GetFile("C:\\img.txt");
  f.Move("E:\\jarvis\\Images\\");
}
catch(err)
{
  alert("file does not exist")
}

This is my program to transfer a file to a specific location and shows alert if it does not exist

Solution 11 - Javascript

An async call to see if a file exists is the better approach, because it doesn't degrade the user experience by waiting for a response from the server. If you make a call to .open with the third parameter set to false (as in many examples above, for example http.open('HEAD', url, false); ), this is a synchronous call, and you get a warning in the browser console.

A better approach is:

function fetchStatus( address ) {
  var client = new XMLHttpRequest();
  client.onload = function() {
    // in case of network errors this might not give reliable results
    returnStatus( this.status );
  }
  client.open( "HEAD", address, true );
  client.send();
}

function returnStatus( status ) {
  if ( status === 200 ) {
    console.log( 'file exists!' );
  }
  else {
    console.log( 'file does not exist! status: ' + status );
  }
}

source: https://xhr.spec.whatwg.org/

Solution 12 - Javascript

JavaScript function to check if a file exists:

function doesFileExist(urlToFile)
{
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send();
     
    if (xhr.status == "404") {
        console.log("File doesn't exist");
        return false;
    } else {
        console.log("File exists");
        return true;
    }
}

Solution 13 - Javascript

This is an adaptation to the accepted answer, but I couldn't get what I needed from the answer, and had to test this worked as it was a hunch, so i'm putting my solution up here.

We needed to verify a local file existed, and only allow the file (a PDF) to open if it existed. If you omit the URL of the website, the browser will automatically determine the host name - making it work in localhost and on the server:

$.ajax({

    url: 'YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf',
    type: 'HEAD',
    error: function () {
        //file not exists
        alert('PDF does not exist');

    },
    success: function () {
        //file exists
        window.open('YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf', "_blank", "fullscreen=yes");

    }
});

Solution 14 - Javascript

First creates the function

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

After using the function as follows

if($.UrlExists("urlimg")){
	foto = "img1.jpg";
}else{
	foto = "img2.jpg";
}

$('<img>').attr('src',foto);

Solution 15 - Javascript

Here's my working Async Pure Javascript from 2020

function testFileExists(src, successFunc, failFunc) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState === this.DONE) {
            if (xhr.status === 200) {
                successFunc(xhr);
            } else {
                failFunc(xhr);
            }
        }
    }
    // xhr.error = function() {
    //     failFunc(xhr);
    // }
    // xhr.onabort = function() {
    //     failFunc(xhr);
    // }
    // xhr.timeout = function() {
    //     failFunc(xhr);
    // }
    xhr.timeout = 5000;           // TIMEOUT SET TO PREFERENCE (5 SEC)
    xhr.open('HEAD', src, true);
    xhr.send(null);               // VERY IMPORTANT
}
function fileExists(xhr) {
    alert("File exists !!  Yay !!");
}
function fileNotFound(xhr) {
    alert("Cannot find the file, bummer");
}
testFileExists("test.html", fileExists, fileNotFound);

I could not force it to come back with any of the abort, error, or timeout callbacks. Each one of these returned a main status code of 0, in the test above, so I removed them. You can experiment. I set the timeout to 5 seconds as the default seems to be very excessive. With the Async call, it doesn't seem to do anything without the send() command.

Solution 16 - Javascript

What you'd have to do is send a request to the server for it to do the check, and then send back the result to you.

What type of server are you trying to communicate with? You may need to write a small service to respond to the request.

Solution 17 - Javascript

This doesn't address the OP's question, but for anyone who is returning results from a database: here's a simple method I used.

If the user didn't upload an avatar the avatar field would be NULL, so I'd insert a default avatar image from the img directory.

function getAvatar(avatar) {
    if(avatar == null) {
        return '/img/avatar.jpg';
    } else {
        return '/avi/' + avatar;
    }
}

then

<img src="' + getAvatar(data.user.avatar) + '" alt="">

Solution 18 - Javascript

It works for me, use iframe to ignore browsers show GET error message

 var imgFrame = $('<iframe><img src="' + path + '" /></iframe>');
 if ($(imgFrame).find('img').attr('width') > 0) {
     // do something
 } else {
     // do something
 }

Solution 19 - Javascript

I wanted a function that would return a boolean, I encountered problems related to closure and asynchronicity. I solved this way:

checkFileExistence= function (file){
    result=false;
    jQuery.ajaxSetup({async:false});
    $.get(file)
        .done(function() {
           result=true;
        })
        .fail(function() {
           result=false;
        })
    jQuery.ajaxSetup({async:true});
    return(result);
},

Solution 20 - Javascript

You can use this command, I use that for my website.

if (File("patch").exists)
{
    //do jobe when exists
} else {
    // do jobe when dosent exist
}

thanks

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionusertestView Question on Stackoverflow
Solution 1 - JavascriptcichyView Answer on Stackoverflow
Solution 2 - JavascriptMatthew James DavisView Answer on Stackoverflow
Solution 3 - JavascriptTesterView Answer on Stackoverflow
Solution 4 - JavascriptGinoView Answer on Stackoverflow
Solution 5 - JavascriptMoobView Answer on Stackoverflow
Solution 6 - JavascriptNik SumeikoView Answer on Stackoverflow
Solution 7 - JavascriptShaunView Answer on Stackoverflow
Solution 8 - JavascriptJan TuroňView Answer on Stackoverflow
Solution 9 - JavascriptGëzim MusliajView Answer on Stackoverflow
Solution 10 - Javascriptyasir amin 9th-b DR.VSMPSView Answer on Stackoverflow
Solution 11 - JavascriptJim BergmanView Answer on Stackoverflow
Solution 12 - JavascriptAni MenonView Answer on Stackoverflow
Solution 13 - JavascriptJosh HarrisView Answer on Stackoverflow
Solution 14 - JavascriptVladimir SalgueroView Answer on Stackoverflow
Solution 15 - JavascriptblisswebView Answer on Stackoverflow
Solution 16 - JavascriptMadcapLaugherView Answer on Stackoverflow
Solution 17 - JavascripttimgavinView Answer on Stackoverflow
Solution 18 - JavascriptAnhMVView Answer on Stackoverflow
Solution 19 - JavascriptGianlorenzo LenzaView Answer on Stackoverflow
Solution 20 - JavascriptArashView Answer on Stackoverflow