How do I check if a file on my server exists in jQuery or pure JavaScript?
19 Answers
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)
}
-
That won't necessarily tell you whether the file exists or not. There is more than one way for an AJAX request to error. – Gareth Sep 05 '10 at 17:13
-
I know, connection might be down, etc. This you can also check by checking file that you know for sure exist. But question was about something else ;) – cichy Sep 05 '10 at 17:17
-
Yeah, slight improvement would be to check for different status codes inside your error callback method, 404 being the specific one you are referring to, though you probably would care just as much if you got a 500 (internal server error) or a 403 (access denied). – Gabriel Sep 05 '10 at 17:21
-
6in your pure javascript example you should be binding `OnReadyStateChange` event before you check the HTTP_STATUS. – RobertPitt Sep 05 '10 at 18:36
-
9The example code is wrong, and there's nothing whatsoever said about what's going on at the server. The original question is pretty vague, but there's no reason to assume that the server that's running there is in fact mapping URLs directly to the file system. Honestly, I don't see why this answer is so popular as it doesn't really say how to do what the question asked for. – Pointy Sep 05 '10 at 19:34
-
80@Pointy Could be because it resolves something the rest of us are Googling for – Ian Hunter Aug 09 '11 at 22:35
-
why did you use HEAD and not something else ? – Royi Namir Dec 23 '12 at 15:35
-
4@cichy - does this load the file into memory or not? I'm looking to check for existence but not load a file. – Brian Apr 29 '13 at 19:41
-
With the non-jQuery approach the function returns nothing and I get this error: a.html:26NETWORK_ERR: XMLHttpRequest Exception 101: A network error occured in synchronous requests. – Sergey Orshanskiy Oct 14 '13 at 02:45
-
similar stackoverflow question http://stackoverflow.com/questions/16553174/test-if-a-file-exists-with-javascript – Parag Nov 06 '13 at 05:45
-
@Parag it's hard to know that there is duplicate created 3 years later in which there is link to this question marked as "already answered" ;) – cichy Nov 07 '13 at 09:07
-
I would add async:false to the parameters and return false from the error function and true from the success function, that way it could be used as a generic function "checkIfUrlAvailable" which returns true or false – BornToCode Jan 12 '14 at 13:26
-
fyi, you may also need to add dataType: "text". Otherwise it could cause a parsererror – Aaron Oommen Jun 11 '14 at 18:03
-
1@Brian (Royi Namir too): I wondered those same questions, so I looked at the HTTP protocol. [See section 9.4]:(http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4). "The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response." I understand this to mean that HEAD gets metadata, but not the document itself. – Nathan Aug 29 '14 at 13:40
-
1I get Cross-Origin Request Blocked on Firefox – dukevin Sep 04 '14 at 01:59
-
Does the main difference between the standard and jQuery approach is respectively the synchronous and asynchronous behavior ?? – Donatello Oct 03 '14 at 12:25
-
11Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/ (This warning by browser) – kupendra May 28 '15 at 07:15
-
can i check without extension?, else how can i check without extension? – 151291 Feb 02 '16 at 03:37
-
@Donatello in this case yes, but you can also do async with pure JavaScript (that's what the third argument for `http.open()` is for) – Scribblemacher Aug 08 '17 at 11:51
-
Here is a basic demo in jsfiddle: https://jsfiddle.net/KyleKing/6b6d55hq/ – KyleKing Apr 27 '18 at 10:25
-
1Would love to see a plain JavaScript version that doesn't give red HEAD 404 warning in console AND don't use deprecated code <3 – Acidon Dec 11 '18 at 11:02
-
This solution doesn't work if you try to check existance of file located in other domain. – userlond Jan 28 '19 at 07:38
-
The third example does not work for checking if a file DOES NOT exist. If it doesn't exist nothing ever gets called. You can solve this problem with: xhr.addEventListener("error", errorFunc); – blissweb Oct 16 '20 at 04:33
-
This method always gives file found if i deleted the file from the directory – Shashank Dubey Feb 06 '21 at 06:30
A similar and more up-to-date approach.
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})

- 12,134
- 7
- 61
- 90
-
3why is this more up-to-date? `$.ajax` seems better if it is more backward compatible, right? – tim peterson Jul 02 '13 at 14:14
-
17$.ajax works too, but success/error/complete functions are deprecated in favor of promises, done/fail/always methods. read more about it here http://api.jquery.com/jQuery.ajax/. I used get here because we're only interested in a simple get, but this is just shorthand for $.ajax({url:url,type:'GET'}). – Matthew James Davis Jul 02 '13 at 16:29
-
5If the image doesn't exist, the console echo's a 404 error. Is there a way to remove this, because my application is always expecting one image to not exist... – user1534664 Sep 24 '13 at 22:59
-
2Not possible, see: http://stackoverflow.com/a/16379746/1981050. However, this should not interrupt your behavior. It will just yield some extraneous logging. – Matthew James Davis Sep 25 '13 at 14:39
-
-
1
-
does not work for me. Execution seems to take place on a separate thread. .Fail function appears to not be executed in time. – john k Nov 08 '14 at 02:44
-
-
I'm also getting the cross origin error if the file does not exists, but if it does the file is loaded fine. This means either is a cors bug or using ajax for this approach is a hack. What do you think? I mean is your suggestion a proper way to do this? – Chazy Chaz Jan 15 '16 at 00:00
-
All solutions to this problem are basically hack. There is no proper way to check if a file exists only. The code here is designed to actually fetch the resource. However, among all the answers here, this is the most proper one that uses jQuery. – Matthew James Davis Jan 20 '16 at 00:15
-
1
-
@MatthewJamesDavis the success and error functions as used in the accepted answer are not deprecated. They are still perfectly valid if used as part of settings to $.ajax. What is deprecated is the $.ajax().success() and $.ajax.error() functions. Search for "Deprecation Notice" here http://api.jquery.com/jQuery.ajax/ – Vardhaman Deshpande Apr 25 '17 at 12:46
-
I'm pretty sure that 4 years ago, when I wrote this answer, they were deprecated. Thanks for the update, though! To everyone else: Stop using jQuery guys. It's 2017. – Matthew James Davis Apr 28 '17 at 10:06
-
1I don't think they were ever deprecated. A lot of people do have this particular misconception though on what exactly was deprecated. I am happy to be corrected if I am wrong. Agree that jQuery is no longer the go-to js library for web dev, but there are a lot of people still using it due to various reasons. So just thought I should clarify this for them. – Vardhaman Deshpande May 01 '17 at 17:28
-
Weather this work or not, I see a lot of codes in STO like this one with syntax error! – David Hope Nov 17 '17 at 11:57
-
Your ability to identify syntax errors is worse than your mastery of the English language. – Matthew James Davis Nov 19 '17 at 21:02
This works for me:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}

- 797
- 5
- 2
-
2While some other answers are better for their function, I +1 this answer as it is what i was looking for. Just remember, you will always get zero unless you load the content first!. ie: window.addEventListener('load', function(){ – SpiRail Jun 27 '12 at 19:05
-
Actually, I still had issues, even with the window load. Seems like the image cannot be measured until it is cached somehow. Anyway, I doesn't work for me on first time load of the page. (ie: user has never seen this image before). It might work for you if you have the image on a previous page, maybe... – SpiRail Jun 28 '12 at 19:38
-
4That's because it sets the source of the image and IMMEDIATELY checks to see the height of the image which has not finished downloading yet. You'd have to add an onload handler for this to work. This is not a reliable approach for that exact reason. – dudewad Dec 21 '13 at 04:09
-
Why isn't it reliable if you add an img.onload hanlder like so http://stackoverflow.com/a/12355031/988591 ? – Redoman Oct 12 '14 at 08:11
-
-
8The question asks about a **file**, not an image! If the URL does exist and is not a file its height will be 0!! – Apostolos Sep 14 '17 at 06:15
-
var img = new Image(); img.src = image; img.onload = () => { if (img.height){ } else { console.error(image); } } – user3270784 Dec 08 '22 at 10:23
i used this script to add alternative image
function imgError()
{
alert('The image could not be loaded.');
}
HTML:
<img src="image.gif" onerror="imgError()" />

- 1,834
- 2
- 19
- 20
-
28Great -- didn't know that. You can do the following to set a save alternative if an image does not exist:
– Ridcully Jul 26 '12 at 07:24
-
3@Ridcully Ah, but what if the alternative fails? Then you're in an endless loop right? – rvighne Feb 17 '14 at 01:17
-
If the alternative fails, i suppose there's something more wrong on the server side (or on the programmer's side :P) – Erenor Paz Mar 23 '14 at 16:58
-
You could always set the OnError of the img tag to nothing when setting the alt image to prevent the endless loop. – KingOfHypocrites Apr 04 '14 at 16:42
-
-
2Bad news from the future. This is marked as "Deprecated. Not for use in new websites." https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img – keithpjolley Feb 25 '20 at 01:10
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);
-
7
-
2its some more details on the non-jQuery form which can be helpful – tim peterson Jul 02 '13 at 14:12
-
@Moob, its not "effectively the same as the accepted answer", you're sending a GET request, which is way different to HEAD request. – YemSalat Feb 11 '14 at 23:41
-
`async: false`, synchronous operation in Firefox version 30.0 and later, and in recent/current versions of Chrome is deprecated due to unfavorable user experience. Attempted use results in fail/error. Should use `async: true` with callback function for asynchronous operation. – Kevin Fegan Nov 19 '17 at 21:33
-
Please this wait for response before continue to execute further JS? Thank you. – vladanPro Jan 26 '18 at 14:33
-
I like this method better than the official answer. It test for whether the file can be actually accessed. I was looking for something that would take into consideration that the file might exist, but perhaps permission is denied, or one of the many other possible failures. I'm using it in the context of pulling custom style sheets into an app, only if the file can actually be pulled. Up voting. :) – Bytech Aug 31 '19 at 10:19
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

- 8,263
- 8
- 50
- 53
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!

- 1,581
- 2
- 16
- 35
-
3I think this will lose the boolean values because they get returned from the callbacks, not the UrlExists function. – mikebridge Oct 22 '14 at 22:18
-
this can't work, you should read this : http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Hacketo Dec 03 '15 at 12:21
-
All the other answers can fail due to cache!
Making a HTTP request to a file on server can be intercepted with HTTP cache and the cached response is then returned. But the file may be deleted on the server in the meantime, so ignoring cache may return false positive results.
Proper solution would be to create non-cached HTTP HEAD request. Nik Sumeiko's answer uses no-cache
header which means that the response can be cached, but must be revalidated before reuse. In this case the server may return 304: Not Modified
, which is not 200: OK
and thus false negative.
To avoid cache, the correct header is Cache-Control: no-store
File can exist without HTTP 200 response
You should also keep in mind that redirection (301: Moved Permanently
, 307: Temporary Redirect
or 308: Permanent Redirect
) 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. In this case 403: Forbidden
is usually returned, which doesn't mean file does not exist but file is unavailable. Last but not least, the same applies to 500: Internal Server Error
response, which means that the HTTP server failed to handle the request, but the file can be available otherwise, like by FTP.
The following code will return true if the file exists, false if not or undefined if the file is unavailable or redirected:
const fileExists = file =>
fetch(file, {method: 'HEAD', cache: 'no-store'})
.then(response => ({200: true, 404: false})[response.status])
.catch(exception => undefined);
fileExists("yourFile.html").then(yes => yes && alert("yourFile.html exists"));
// or in the async scope...
let yourFileExists = await fileExists("yourFile.html");
if(yourFileExists) console.log("It is there!")
else if(yourFileExists===false) console.log("Nope, it was deleted.");
else console.log("You are not worthy the answer, puny human!");
Modern and obsolete approaches
Since we live in the future now, I would also recommend:
$.ajax()obsolete, don't use in new projectsXMLHttpRequest()obsolete, don't use in new projects- fetch() modern approach, use it if you are free to choose
Note GET/POST methods (like <img src...>
) are not appropriate here as they waste network traffic by downloading the file (imagine the worst scenario with high resolution photo and user with paid mobile data in area with poor connectivity)
Note Modern PWA approach is to use Cache API with serviceWorker's fetch event which intercepts the communication between the client and HTTP cache. In the example in the link, there should be something like
if(event.request.cache=="no-store") {
// avoid cache storage and pass the request in the chain
// client - cache storage - HTTP cache - server
return fetch(event.request);
}
Without this, the cache settings may be ignored and there may be no way to detect the remote file existence from the main thread with the serviceWorker running - illustrated here.

- 31,451
- 23
- 125
- 169
-
Great code -- note that if you want to use this method on major android mobile browsers, only 2022 browser updates can handle it. You may want to check if 'fetch' exists (detect to use older methods if needed) in order to include those. See https://caniuse.com/fetch – Jeff Clayton May 17 '22 at 13:35
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;
}
}

- 27,209
- 16
- 105
- 126
-
-
I'd personally replace the final if clause with simply `return xhr.status == 200;` to turn it into a function returning a boolean result and also treating server errors as pointing towards inaccessible files. – Jonas Jan 02 '23 at 13:33
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 <

- 86
- 3
- 5
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

- 17,306
- 24
- 81
- 109
-
1If you're going to use FileSystemObject it seems easier to use the FileExists() method. http://msdn.microsoft.com/en-us/library/aa265024(v=vs.60).aspx – Mark F Guerra Jan 17 '14 at 18:53
-
1`ActiveXObject` is only available in Internet Explorer, so this won't work in other browsers. – Anderson Green Aug 30 '21 at 18:11
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/

- 5,207
- 2
- 17
- 19
-
I also get a warning response in the console log with your method, any idea ? – Pierre Oct 26 '17 at 06:22
-
Try calling `.open` with the third parameter set to `true` to make sure it calls it asynchronously, like this `client.open("HEAD", address, true);` @Pierre – Jim Bergman Oct 31 '17 at 01:07
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");
}
});

- 446
- 4
- 8
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);

- 5,609
- 3
- 42
- 47
-
I tried [*here*](http://jsfiddle.net/PMrDn/1160/) but could not get it work. What I have been missing? – eQ19 Mar 24 '15 at 16:59
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.

- 3,037
- 3
- 22
- 33
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.

- 573
- 2
- 8
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="">

- 4,972
- 4
- 36
- 48
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
}

- 11
- 3
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);
},
-
Still can not manage properly detect file existence without using jQuery. I tried all approaches listed above. Status always 200, regardless file existence. – Serg Jul 05 '20 at 20:11