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 a开发者_StackOverflow社区dvance!
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.
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.
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.
精彩评论