How do I check if file exists in jQuery or pure Ja

2018-12-31 04:10发布

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

17条回答
闭嘴吧你
2楼-- · 2018-12-31 04:36

This works for me:

function ImageExist(url) 
{
   var img = new Image();
   img.src = url;
   return img.height != 0;
}
查看更多
春风洒进眼中
3楼-- · 2018-12-31 04:37

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

查看更多
余欢
4楼-- · 2018-12-31 04:38

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.

查看更多
旧时光的记忆
5楼-- · 2018-12-31 04:39

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

查看更多
素衣白纱
6楼-- · 2018-12-31 04:40

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
 }
查看更多
素衣白纱
7楼-- · 2018-12-31 04:41

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 the avatar field would be NULL, so I'd insert a default avatar image from the img directory.

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

then

<img src="' + getAvatar(data.user.avatar) + '" alt="">
查看更多
登录 后发表回答