ExceptionSlayer ExceptionSlayer - 1 year ago 319
HTML Question

Check if a file exists locally using javascript ONLY

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.

Any answers are appreciated.

by the way, I am making a titanium app for Mac so I am looking for a way of protecting my files from people who click "show package contents".

Answer Source

Your question is ambiguous, so there are multiple possible answers depending on what you're really trying to achieve.

If you're developping as I'm guessing a desktop application using Titanium, then you can use the FileSystem module's getFile to get the file object, then check if it exists using the exists method.

Here's an example taken from the Appcelerator website:

var homeDir = Titanium.Filesystem.getUserDirectory();
var mySampleFile = Titanium.Filesystem.getFile(homeDir, 'sample.txt');

if (mySampleFile.exists()) {
    alert('A file called sample.txt already exists in your home directory.');

Check the getFile method reference documentation

And the exists method reference documentation

For those who thought that he was asking about an usual Web development situation, then thse are the two answers I'd have given:

1) you want to check if a server-side file exists. In this case you can use an ajax request try and get the file and react upon the received answer. Although, be aware that you can only check for files that are exposed by your web server. A better approach would be to write a server-side script (e.g., php) that would do the check for you, given a filename and call that script via ajax. Also, be aware that you could very easily create a security hole in your application/server if you're not careful enough.

2) you want to check if a client-side file exists. In this case, as pointed you by others, it is not allowed for security reasons (although IE allowed this in the past via ActiveX and the Scripting.FileSystemObject class) and it's fine like that (nobody wants you to be able to go through their files), so forget about this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download