Check if a file exists locally using JavaScript only

后端 未结 10 1684
盖世英雄少女心
盖世英雄少女心 2020-12-03 14:01

I want to check if a file exists locally, where the HTML file is located. It has to be JavaScript. JavaScript will never be disabled. jQuery is not good but can do.

10条回答
  •  遥遥无期
    2020-12-03 14:20

    Since 'Kranu' helpfully advises 'The only interaction with the filesystem is with loading js files . . .', that suggests doing so with error checking would at least tell you if the file does not exist - which may be sufficient for your purposes?

    From a local machine, you can check whether a file does not exist by attempting to load it as an external script then checking for an error. For example:

    File exists? 
    
    

    Some notes...

    • append some random data to the file name (url+="?"+new Date etc) so that the browser cache doesn't serve an old result.
    • set a unique element id (el.id=) if you're using this in a loop, so that the get_error function can reference the correct item.
    • setting the onerror (el.onerror=function) line is a tad complex because one needs it to call the get_error function AND pass el.id - if just a normal reference to the function (eg: el.onerror=get_error) were set, then no el.id parameter could be passed.
    • remember that this only checks if a file does not exist.

提交回复
热议问题