Saturday, April 23, 2005

Using JavaScript to read a client-side file

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/using_javascript_to_read_a_clientside_file.htm]

One of the benefits of blogs is that you get to write about oddball topics just for fun. One such topic is using JavaScript to read a client-side file. Initially this wasn't possible - JavaScript was not designed to allow this due to security concerns. Imagine a malicious app reading/writing all your important system files! It is certainly not advisable due to security concerns. A good security overview of JavaScript is in the "Security" section at: http://www.quirksmode.org/js/intro.html

Most of the time if you do need a client file, you could use ASP.Net's file uploaded control to upload files from the client to the server.

However, it is still possible for JavaScript to read client files using ActiveX:

function ReadFromFile() {
    var strContent = ReadFileToString(document.Form1.TxtFileName.value);
    document.Form1.HdnContent.value = strContent;
    document.Form1.submit();
}

function ReadFileToString(strFileName) {
    var strContents;
    strContents = "";

    objFSO = new ActiveXObject("Scripting.FileSystemObject");
    if (objFSO.FileExists(strFileName)) {
        strContents = objFSO.OpenTextFile(strFileName, 1).ReadAll();
    }
   
    return strContents;
} //end of function

This script first uses the ActiveX Scripting.FileSystemObject to read the file, then stores the contents in a hidden field, and lastly submits to the server so it can do whatever it needs with that client data.

Note that you'll need to enable ActiveX objects in the browser, else you'll get an error like: "Error: Number:-2146827859 Description:Automation server can't create object". You can do this by:

  1. In Internet Explorer > Tools > Internet Options > Security > Custom Level
  2. Enabling or prompting "Initializing and Script Activex controls not marked as safe"

While this is a cute trick to know, again I emphasize be cautious of using it in any enterprise app due to security reasons.

No comments:

Post a Comment