How do I check if a file on my server exists in jQuery or pure JavaScript?
如何检查服务器上的文件是jQuery还是纯JavaScript存在?
16 个解决方案
#1
377
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(成功),而不是。
#2
60
A similar and more up-to-date approach.
一种类似的、更先进的方法。
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})
#3
57
This works for me:
这工作对我来说:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
#4
39
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()" />
http://wap.w3schools.com/jsref/event_onerror.asp
http://wap.w3schools.com/jsref/event_onerror.asp
#5
17
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.
请注意,这个示例使用的是GET请求,除了获取头(您需要检查文件是否存在)之外,它还获取整个文件。如果文件足够大,这个方法需要一段时间才能完成。
The better way to do this would be changing this line: req.open('GET', url, false);
to req.open('HEAD', url, false);
更好的方法是改变这条线:req。打开(‘得到’,url,假);要求的事情。打开(“头”,url,假);
#6
14
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!
看起来效果不错,希望这能帮助到别人!
#7
3
Here's how to do it ES7 way, if you're using Babel transpiler or Typescript 2:
如果你正在使用Babel transpiler或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:
然后在您的其他异步作用域内,您可以轻松地检查url是否存在:
const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');
console.log(isValidUrl); // true || false
#8
2
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 <
未捕获的语法错误:意外令牌<
#9
1
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
这是我将文件传输到特定位置的程序,如果文件不存在,将显示警告
#10
1
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);
#11
1
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;
}
}
#12
1
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:
我们需要验证本地文件是否存在,并且只允许文件(PDF)在存在时打开。如果您省略了网站的URL,浏览器将自动确定主机名——使其在localhost和服务器上工作:
$.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");
}
});
#13
0
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.
您试图与哪种类型的服务器通信?您可能需要编写一个小服务来响应请求。
#14
0
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.
这并没有解决OP的问题,但是对于任何从数据库返回结果的人来说:我使用了一个简单的方法。
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.
如果用户没有上传头像,头像字段将为空,所以我将从img目录中插入一个默认的头像图像。
function getAvatar(avatar) {
if(avatar == null) {
return '/img/avatar.jpg';
} else {
return '/avi/' + avatar;
}
}
then
然后
<img src="' + getAvatar(data.user.avatar) + '" alt="">
#15
0
It works for me, use iframe to ignore browsers show GET error message
它适用于我,使用iframe忽略浏览器显示的GET错误消息
var imgFrame = $('<iframe><img src="' + path + '" /></iframe>');
if ($(imgFrame).find('img').attr('width') > 0) {
// do something
} else {
// do something
}
#16
0
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.
查看文件是否存在的异步调用是更好的方法,因为它不会因为等待服务器响应而降低用户体验。如果您调用.open并将第三个参数设置为false(如上面的许多示例中所示,例如http)。打开(“头”,url,假);),这是一个同步调用,您将在浏览器控制台中得到警告。
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/
来源:https://xhr.spec.whatwg.org/
#1
377
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(成功),而不是。
#2
60
A similar and more up-to-date approach.
一种类似的、更先进的方法。
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})
#3
57
This works for me:
这工作对我来说:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
#4
39
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()" />
http://wap.w3schools.com/jsref/event_onerror.asp
http://wap.w3schools.com/jsref/event_onerror.asp
#5
17
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.
请注意,这个示例使用的是GET请求,除了获取头(您需要检查文件是否存在)之外,它还获取整个文件。如果文件足够大,这个方法需要一段时间才能完成。
The better way to do this would be changing this line: req.open('GET', url, false);
to req.open('HEAD', url, false);
更好的方法是改变这条线:req。打开(‘得到’,url,假);要求的事情。打开(“头”,url,假);
#6
14
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!
看起来效果不错,希望这能帮助到别人!
#7
3
Here's how to do it ES7 way, if you're using Babel transpiler or Typescript 2:
如果你正在使用Babel transpiler或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:
然后在您的其他异步作用域内,您可以轻松地检查url是否存在:
const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');
console.log(isValidUrl); // true || false
#8
2
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 <
未捕获的语法错误:意外令牌<
#9
1
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
这是我将文件传输到特定位置的程序,如果文件不存在,将显示警告
#10
1
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);
#11
1
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;
}
}
#12
1
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:
我们需要验证本地文件是否存在,并且只允许文件(PDF)在存在时打开。如果您省略了网站的URL,浏览器将自动确定主机名——使其在localhost和服务器上工作:
$.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");
}
});
#13
0
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.
您试图与哪种类型的服务器通信?您可能需要编写一个小服务来响应请求。
#14
0
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.
这并没有解决OP的问题,但是对于任何从数据库返回结果的人来说:我使用了一个简单的方法。
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.
如果用户没有上传头像,头像字段将为空,所以我将从img目录中插入一个默认的头像图像。
function getAvatar(avatar) {
if(avatar == null) {
return '/img/avatar.jpg';
} else {
return '/avi/' + avatar;
}
}
then
然后
<img src="' + getAvatar(data.user.avatar) + '" alt="">
#15
0
It works for me, use iframe to ignore browsers show GET error message
它适用于我,使用iframe忽略浏览器显示的GET错误消息
var imgFrame = $('<iframe><img src="' + path + '" /></iframe>');
if ($(imgFrame).find('img').attr('width') > 0) {
// do something
} else {
// do something
}
#16
0
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.
查看文件是否存在的异步调用是更好的方法,因为它不会因为等待服务器响应而降低用户体验。如果您调用.open并将第三个参数设置为false(如上面的许多示例中所示,例如http)。打开(“头”,url,假);),这是一个同步调用,您将在浏览器控制台中得到警告。
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/
来源:https://xhr.spec.whatwg.org/