Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Mar 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Checking File is exists or not by using JavaScript?

    Hai Forum,

    May be this question is not in correct format,
    I want to know about how to check a particular file is exists or not ? using Javascript.One thing without using ActiveXObject because it is supports in IE only.

    Thanking You,
    Santosh Srinivas.G

  • #2
    Banned
    Join Date
    Mar 2012
    Posts
    306
    Thanks
    1
    Thanked 28 Times in 28 Posts
    If the file is on the server then you can use AJAX. If it's on the user's local machine then I don't think you can do it other than how you said you don't want to use.

  • #3
    Regular Coder
    Join Date
    Aug 2010
    Posts
    974
    Thanks
    19
    Thanked 212 Times in 210 Posts
    Code:
    function exists?(strURL){
      req = new XMLHttpRequest;
      req.open("HEAD", strURL, false);
      req.send();
      return (req.status==404) ? false : true;
    }

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,613
    Thanks
    80
    Thanked 4,634 Times in 4,596 Posts
    Note that Davey's answer only works if the file is on the same server that the web page came from. And even then only if the file is accessible via HTTP (that is, not in some directory that the web server is disallowed access to). But yes, it's by far the easiest way to do this.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,460
    Thanks
    11
    Thanked 600 Times in 580 Posts
    one minor point of clarification:

    javascript can see files from the same origin as the page the user is looking at. If you are serving the html page from a local file, then you indeed CAN check for files locally. If your html runs on an http server, you can only use ajax to look for file on that server.


    in the case of local files, a code like the one posted will work.
    IE doesn'y do status correctly, and there's also no 404s to contend with:


    Code:
    function exists(strURL){
      var req = new XMLHttpRequest;
      req.open("GET", strURL, false);
      req.send();
      return !! req.responseText;
    }
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •