Javascript handling local file system

Wednesday, May 14, 2008 by Admin

A lot of web programmers would want a easy way to handle files on the client machine to suit their designs, for example, storing a temporary config file to be retrieved each time when users visit their site(which can be easily achieved by using cookies), setting a default upload file with the from file type to show user what to upload, etc. Some of them could be cool ideas, but how can you achieve these using javascript?

Well, the answer is, no. Javascript is a useful client side scripting language, but for security reasons, reading/writing files on the client machines is not allowed. If it is allowed, you will never know what the script writes to your files and what files it reads. Those files could contains sensitive system or personal information, which is a very serious security issue. At the same time, script could write unsuitable data into any of your files and do damage to your system.

So, what about the setting form file issue? Got any ideas?
Say if you got a input for file upload.

<input type="file" name="myfile"/>

You can never do something like

document.myform.myfile.value = "gotcha.txt";

You can only get the value but not set the value with this properties.
The idea is just similar. If it’s allowed to be set by javascript, you can actually do something as bad as you can imagine. Say if there’s a script runs upon page onload event

document.myform.myfile.value = "c:\windows\system32\anythingIwant.txt";
document.myform.submit();

Yay! I can get anything I want from the visitor’s computer! And the user won’t even notice!
Of course the Javascript team also realized it. So you can see why it is not allowed to be done by javascript.
Form file input type can be set only by user clicking the browse button and select then the target files but not any other ways.

So you figured it out that all the above imaginations could not be done. Are there any workarounds?
Some of the ideas about storing visitor configs and behaviors can be achieved by using cookies. Cookies are lists of keys and pairs stored in cookie files accessible by browsers. Isn’t it just something you expected? I am not going to talk about it here, if you are interested to know, just do some googling and lot of information would show up immediately.
For the setting input file bit, I am afraid it cannot be done in anyway. But you can remind visitors about the upload files requirements in text so they would know what to be uploaded.

To conclude, in order to provide a secure environment for web surfers and avoid any mischievous attempts, you are not allowed to access any client side local files unless users upload them actively. It does not only applies to javascripts but most of the scripting languages. You should understand this is just for doing everyone good, at least your files would not be stolen by me when you are reading this article. >:)