Sometimes we want to upload a file through the path of the file, but few times the file does not exist. In that case, we have to respond to users the given path does not find any file or does not exist in the mentioned file.
Approach 1: Use ajax() method of jQuery to check if a file exists on a given URL or not. The ajax() method is used to trigger the asynchronous HTTP request. If the file exists, ajax() method will in turn call ajaxSuccess() method else it will call Error function.
- Example: This example illustrate the above approach.
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
How to check if file exist using jquery
</
title
>
<
script
src
=
</
script
>
<
style
>
body {
text-align: center;
}
h1 {
color: green;
}
#output {
color: green;
font-size: 20px;
font-weight: bold;
}
</
style
>
</
head
>
<
body
>
<
h1
>
neveropen
</
h1
>
<
label
id
=
"File_Path"
>
<
b
>Enter File Path:</
b
>
</
label
>
<
input
type
=
"text"
id
=
"File_URL"
>
<
button
id
=
"Check_File"
>
click here
</
button
>
<
p
id
=
"output"
></
p
>
<
script
>
$(document).ready(function() {
$("#Check_File").click(function() {
var url = $("#File_URL").val();
if (url != "") {
$.ajax({
url: url,
type: 'HEAD',
error: function()
{
$("#output").text("File doesn't exists");
},
success: function()
{
$("#output").text('File exists');
}
});
} else {
$("#Output").text("Please enter File URL");
}
});
});
</
script
>
</
body
>
</
html
>
- Output:
Approach 2: Use XMLHttpRequest() method to trigger ajax request. If the HTTP status is 200 then file exists otherwise file is not present.
- Example: This example illustrate the above approach.
<!DOCTYPE HTML>
<
html
>
<
head
>
<
title
>
How to check if file exist or
not on HTTP status is 200
</
title
>
<
style
>
body {
text-align: center;
}
h1 {
color: green;
}
#output {
color: green;
font-size: 20px;
font-weight: bold;
}
</
style
>
</
head
>
<
body
>
<
h1
>
neveropen
</
h1
>
<
label
id
=
"File_Path"
>
<
b
>Enter File Path: </
b
>
</
label
>
<
input
type
=
"text"
id
=
"File_URL"
>
<
button
id
=
"Check_File"
onclick
=
"checkFileExist()"
>
click here
</
button
>
<
p
id
=
"output"
></
p
>
<
script
>
var url = document.getElementById("File_URL");
var output = document.getElementById("output");
var http = new XMLHttpRequest();
function checkFileExist() {
if (url.length === 0) {
output.innerHTML = "Please enter File URL";
} else {
http.open('HEAD', url, false);
http.send();
if (http.status === 200) {
output.innerHTML = "File exists";
} else {
output.innerHTML = "File doesn't exists";
}
}
}
</
script
>
</
body
>
</
html
>
- Output: HTTP status is not 200 so if the file exist it will show not exist until the status is 200.
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.