如何检查文件是否存在于 jQuery 或纯 JavaScript 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3646914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check if file exists in jQuery or pure JavaScript?
提问by usertest
How do I check if a file on my server exists in jQuery or pure JavaScript?
如何检查我的服务器上的文件是否存在于 jQuery 或纯 JavaScript 中?
回答by cichy
With jQuery:
使用 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
这是检查 404 状态的代码,不使用 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.
小的变化,它可以检查状态 HTTP 状态代码 200(成功),而不是。
EDIT 2: Since sync XMLHttpRequest is deprecated, you can add a utility method like this to do it async:
编辑 2:由于不推荐使用同步 XMLHttpRequest,您可以添加这样的实用程序方法来异步执行:
function executeIfFileExist(src, callback) {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
callback()
}
}
xhr.open('HEAD', src)
}
回答by Matthew James Davis
A similar and more up-to-date approach.
一种类似且更新的方法。
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})
回答by Tester
This works for me:
这对我有用:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
回答by Gino
i used this script to add alternative image
我用这个脚本来添加替代图像
function imgError()
{
alert('The image could not be loaded.');
}
HTML:
HTML:
<img src="image.gif" onerror="imgError()" />
回答by Moob
So long as you're testing files on the same domainthis 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.
请注意,此示例使用 GET 请求,除了获取标题(检查文件是否存在所需的所有内容)之外,还获取整个文件。如果文件足够大,此方法可能需要一段时间才能完成。
The better way to do this would be changing this line: req.open('GET', url, false);to req.open('HEAD', url, false);
更好的方式来做到这一点会改变这行:req.open('GET', url, false);到req.open('HEAD', url, false);
回答by Shaun
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!
它似乎工作得很好,希望这对某人有所帮助!
回答by Nik Sumeiko
Here's how to do it ES7 way, if you're using Babel transpiler or Typescript 2:
如果您使用的是 Babel 转译器或 Typescript 2,请按照 ES7 的方式进行操作:
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 asyncscope, you can easily check whether url exist:
然后在您的其他async范围内,您可以轻松检查 url 是否存在:
const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');
console.log(isValidUrl); // true || false
回答by G?zim Musliaj
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.
请注意,当被检查的文件不包含 JSON 时,将引发以下语法错误。
Uncaught SyntaxError: Unexpected token <
未捕获的语法错误:意外的标记 <
回答by Jim Bergman
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 .openwith 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.
异步调用以查看文件是否存在是更好的方法,因为它不会通过等待服务器的响应来降低用户体验。如果您.open在将第三个参数设置为 false 的情况下进行调用(如在上面的许多示例中,例如http.open('HEAD', url, false);),这是一个同步调用,并且您会在浏览器控制台中收到警告。
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/
回答by Ani Menon
JavaScript function to check if a file exists:
用于检查文件是否存在的 JavaScript 函数:
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;
}
}

