如何使用JavaScript或JQuery检测一个URL文件是否存在?

如何使用JavaScript或JQuery检测一个URL文件是否存在?

How do I check if file exists in jQuery or JavaScript?

问题:

如何检查服务器上的文件是否在jQuery或JavaScript中?

答案:

使用jQuery:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

编辑:

这是不使用jQuery即可检查404状态的代码

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

进行较小的更改,它可以检查状态HTTP状态代码200(成功)。

 

答案:

一种类似且最新的方法。

$.get(url)
    .done(function() { 
        // exists code 
    }).fail(function() { 
        // not exists code
    })

 

答案:

这对我有用:

function ImageExist(url) 
{
   var img = new Image();
   img.src = url;
   return img.height != 0;
}

 

答案:

我使用此脚本添加替代图像

function imgError()
{
alert('The image could not be loaded.');
}

HTML:

<img src="image.gif" onerror="imgError()" />

http://wap.w3schools.com/jsref/event_onerror.asp

 

答案:

只要您在同一个域上测试文件,它就应该起作用:

function fileExists(url) {
    if(url){
        var req = new XMLHttpRequest();
        req.open('GET', url, false);
        req.send();
        return req.status==200;
    } else {
        return false;
    }
}

请注意,此示例使用的是GET请求,除了获取标头(您需要检查文件是否存在的所有内容)之外,还获取整个文件。
如果文件足够大,则此方法可能需要一段时间才能完成。

更好的方式来做到这一点会改变这行:req.open('GET', url, false);req.open('HEAD', url, false);

 

答案:

尝试运行此问题的答案时遇到了跨域权限问题,因此我选择了:

function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
    return true;
}).bind('error', function() {
    return false;
});
}

看来效果很好,希望这对某人有帮助!

 

答案:

如果您使用的是Babel Transpiler或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;
  }
}

然后,在其他async作用域内,您可以轻松地检查url是否存在:

const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');

console.log(isValidUrl); // true || false

 

答案:

您要做的就是向服务器发送请求以进行检查,然后将结果发送回给您。

您尝试与哪种类型的服务器通信?您可能需要编写一个小型服务来响应请求。

 

答案:

对于客户端计算机,可以通过以下方式实现:

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")
}

这是我的程序,用于将文件传输到特定位置,并在不存在文件时显示警报

 

答案:

首先创建功能

$.UrlExists = function(url) {
	var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

使用如下功能后

if($.UrlExists("urlimg")){
	foto = "img1.jpg";
}else{
	foto = "img2.jpg";
}

$('<img>').attr('src',foto);

 

答案:

这没有解决OP的问题,但是对于从数据库返回结果的任何人:这是我使用的一种简单方法。

如果用户未上传头像,则avatar字段为NULL,因此我将从img目录中插入默认的头像图像。

function getAvatar(avatar) {
    if(avatar == null) {
        return '/img/avatar.jpg';
    } else {
        return '/avi/' + avatar;
    }
}

然后

<img src="' + getAvatar(data.user.avatar) + '" alt="">

 

答案:

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;
    }
}

 

答案:

我使用此脚本来检查文件是否存在(它也可以处理跨源问题):

$.ajax(url, {
       method: 'GET',
       dataType: 'jsonp'
         })
   .done(function(response) { 
        // exists code 
    }).fail(function(response) { 
        // doesnt exist
    })

请注意,当检查的文件不包含JSON时,将引发以下语法错误。

未捕获到的SyntaxError:意外令牌<

答案:

它对我有用,使用iframe忽略浏览器显示GET错误消息

 var imgFrame = $('<iframe><img src="' + path + '" /></iframe>');
 if ($(imgFrame).find('img').attr('width') > 0) {
     // do something
 } else {
     // do something
 }

 

答案:

异步调用以查看文件是否存在是更好的方法,因为它不会通过等待服务器的响应来降低用户体验。如果您.open在第三个参数设置为false的情况下进行调用(例如,在上面的许多示例中http.open('HEAD', url, false);),则这是同步调用,并且您会在浏览器控制台中收到警告。

更好的方法是:

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 );
  }
}

Questions:

How do I check if a file on my server exists in jQuery or JavaScript?

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.

Answers:

A similar and more up-to-date approach.

$.get(url)
    .done(function() { 
        // exists code 
    }).fail(function() { 
        // not exists code
    })

Answers:

This works for me:

function ImageExist(url) 
{
   var img = new Image();
   img.src = url;
   return img.height != 0;
}

Answers:

i used this script to add alternative image

function imgError()
{
alert('The image could not be loaded.');
}

HTML:

<img src="image.gif" onerror="imgError()" />

http://wap.w3schools.com/jsref/event_onerror.asp

Answers:

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);toreq.open('HEAD', url, false);

Answers:

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!

Answers:

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 otherasyncscope, you can easily check whether url exist:

const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');

console.log(isValidUrl); // true || false

Answers:

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.

Answers:

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

Answers:

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);

Answers:

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 theavatarfield would beNULL, so I’d insert a default avatar image from theimgdirectory.

function getAvatar(avatar) {
    if(avatar == null) {
        return '/img/avatar.jpg';
    } else {
        return '/avi/' + avatar;
    }
}

then

<img src="' + getAvatar(data.user.avatar) + '" alt="">

Answers:

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;
    }
}

Answers:

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 <

Answers:

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
 }

Answers:

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 examplehttp.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 );
  }
}
发布了153 篇原创文章 · 获赞 803 · 访问量 38万+

猜你喜欢

转载自blog.csdn.net/Aria_Miazzy/article/details/103876362
今日推荐