如何使用JavaScript/jQuery检查Mentioned文件是否存在
有时我们想通过文件的路径来上传一个文件,但少数时候文件并不存在。在这种情况下,我们必须回应用户,给定的路径没有找到任何文件或不存在所述文件。
方法1:使用jQuery的ajax()方法来检查一个文件是否存在于给定的URL上。ajax()方法是用来触发异步HTTP请求的。如果文件存在,ajax()方法将反过来调用ajaxSuccess()方法,否则它将调用**Error函数。
- 例子。这个例子说明了上述方法。
<!DOCTYPE html>
<html>
<head>
<title>
How to check if file exist using jquery
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<style>
body {
text-align: center;
}
h1 {
color: green;
}
#output {
color: green;
font-size: 20px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>
GeeksforGeeks
</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>
- 输出:
方法2:使用XMLHttpRequest()方法来触发ajax请求。如果HTTP状态是200,则文件存在,否则文件不存在。
- 例子。这个例子说明了上述方法。
<!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>
GeeksforGeeks
</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>
- 输出。HTTP状态不是200,所以如果文件存在,它将显示不存在,直到状态为200。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。