views:

102

answers:

4

Hi,

I have to read the first couple of lines of a csv file client side to present the user with a preview before uploading a large file.

I'm using c# with ASP.Net (VS2010)

Does anyone know how this can be done? Also that it works in all browsers!?!

(It's not possible to use activeX or so, we do not want our clients to install something!)

A sample code would be great!

Thanks in advance!

+1  A: 

You can't read a local file with vanilla JavaScript.

You could use activeX as a progressive enhancement to those using IE (even though offering an enhanced experience to IE users goes against everything I stand for!).

If you can use Flash, look at Read local file in Flash.

Skilldrick
Ok but is there another method to read the file??
CyberK
+1  A: 

No, you can't use javascript to read files off the user's machine. You'll have to have help from something like Flash or Java if you want a cross-browser way to do this.

lincolnk
+2  A: 

Firefox 3.6+ and Chrome (at least version 6, possibly older versions) support the File API which lets you read local files from a file input.

Here's a quick sample:

function handleFile(file) {
    var reader = new FileReader();
    reader.onload = function(e) {
        // Here's where you would parse the first few lines of the CSV file
        console.log(e.target.result);
    };
    reader.readAsText(file);
}

in your html, you would have something like this:

<input type="file" onchange="handleFile(this.files[0])" />

Of course, in real life you should make it degrade gracefully.

The file object has name and type properties that you could use to verify that it's a CSV file if you wanted to be more strict.

Matthew Crumley
Thanks... This was the answer I was looking for :D
CyberK
Another question, is it also possible to load the first say 5 lines of a csv without loading the complete csv? And if so, can you give me an example? Thanks
CyberK
@CyberK: I don't think there's a way to read just part of the file. You would have to read the whole thing, find where the 5th line ends, and use `substring` to get just the beginning.
Matthew Crumley
Ok I'm figuring this out.. If I find a solution, I will post it here... Thanks again!
CyberK
+1  A: 

There is a W3C proposal for a File API in HTML5. I ran a few browsers against this test, and found that Firefox 3.6, and Chrome 6 support File Reader API and Local Storage. Safari 5 (on Windows) supported Local Storage but not File Reader API. Sorry I couldn't test IE9 as corporate policy has IE6 (?!) nailed in place.

unhillbilly