Reputation: 121
I need to select a csv file from local file system and display the contents of that file as text using jquery.
I am using this for file Upload
<input id = "uploadCSV" type = "file" />
On its change event,
$('#uploadCSV').change(function(e) {
if(e.target.files != undefined) {
var reader = new FileReader();
reader.onload = function(e) {
var lineSplit = e.target.result.split("\n");
var commaSplit = lineSplit[0].split(",");
var content = "";
for(var i = 0; i < commaSplit.length; i++) {
var temp = commaSplit[i];
content = content + " " + temp;
}
};
reader.readAsText(e.target.files.item(0));
var fileContent = reader.result;
alert(fileContent);
}
});
Somehow this doesn't work and I get null in alert when I use Firefox. If I use IE8, it crashes as it cannot locate e.target.result. Please advise
I am looking for the simplest way of converting a csv file in my local file system into plain text.
Thanks
Upvotes: 1
Views: 3018
Reputation: 121
I could resolve the issue by using asp.net mvc. See below for details
@using(Html.BeginForm("ProcessCsv","<YourControllerName>",FormMethod.Post, new {enctype = multipart/form-data" }))
{
<input id = "myUpload" type = "file" name = "fileBaseParam"/>
<input id = "btnSubmit" type = "submit" name = "ProcessCsv" value = "Submit" />
}
In your controller, define an actionresult,
[HttpPost]
public ActionResult ProcessCsv(HttpPostedFileBase fileBaseParam)
{
var csvReader = new StreamReader(fileBaseParam.InputStream);
string fileContent = csvReader.ReadToEnd();
}
HttpPostedFileBase is the crucial concept here.. You can find more information on this from http://www.codeproject.com/Articles/442515/Uploading-and-returning-files-in-ASP-NET-MVC.
Hope this information would help someone in future.
Thanks
Upvotes: 0
Reputation: 36081
You are alerting the reader.result outwith the onload event handler, you need to move the alert inside the event handler for this to work.
What you are doing just now will alert the reader.result before the file is loaded, at which point results will be null.
To avoid any errors with FileReader not being supported, do a check if (window.FileReader)
before using it.
Change it to:
if ((window.FileReader) && (e.target.files != undefined)) {
var reader = new FileReader();
reader.onload = function(e) {
var lineSplit = e.target.result.split("\n");
var commaSplit = lineSplit[0].split(",");
var content = "";
for(var i = 0; i < commaSplit.length; i++) {
var temp = commaSplit[i];
content = content + " " + temp;
}
var fileContent = reader.result;
alert(fileContent);
};
reader.readAsText(e.target.files.item(0));
}
Upvotes: 1
Reputation: 2837
FileReader is not supported in IE<10 (https://developer.mozilla.org/en-US/docs/DOM/FileReader -- see "Browser Support" at the bottom). If your solution is targeting IE8, then there is no way to do what you are trying to do in Javascript. You'll either have to use an embedded application like Flash, or post the file to your server and return the result.
Upvotes: 0