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
    967
    Thanks
    19
    Thanked 211 Times in 209 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
    25,189
    Thanks
    75
    Thanked 4,341 Times in 4,307 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,296
    Thanks
    10
    Thanked 584 Times in 565 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 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%


  •  

    Posting Permissions

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