0

I am trying to read CSV file on Client Side, my code works fine with modern browsers with FileAPI however I need to figure out a way to support IE8 and IE9. Any help is appreciated.

Upload Control Used:

<input type="file" id ="uplaodFile"/>

JS: for Firefox :

var reader = new FileReader();
./.......
 reader.readAsText(e.target.files.item(0));

For IE : ?????

Mrchief
  • 75,126
  • 20
  • 142
  • 189
user428747
  • 307
  • 2
  • 7
  • 22
  • using flash or active x check `http://stackoverflow.com/questions/5135610/reading-a-txt-file-from-javascript` – Sunand Sep 05 '14 at 19:37
  • 2
    you can upload the file to a server and echo without flash or security warnings. – dandavis Sep 05 '14 at 19:46
  • Can you please elaborate on Ajax method to upload a file to server and echo it back as that is what i am looking at so that i dont cause any Security issues. – user428747 Sep 05 '14 at 19:51
  • For async file uploads I would use [jQuery Form Plugin](http://malsup.com/jquery/form/) or [Kendo UI Upload widget](http://demos.telerik.com/kendo-ui/upload/index). – Dave Sep 09 '14 at 15:20
  • Please note that some CSV files allow newline characters in a string, requiring an elaborate CSV token parser (can't do it with a regex for instance). Please note that if it's a CSV from an Excel file, it might use semi-colons instead of regular colons. – Cœur Sep 16 '14 at 09:42

3 Answers3

1

"Can you please elaborate on Ajax method to upload a file to server and echo it back as that is what i am looking at so that i dont cause any Security issues." -user428747

Given a .csv file , e.g., from Wikipedia - Comma-separated values - Example

csv

Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00

html

<pre></pre>

js

$(function () {
    var url = "file.csv";

    $.getJSON("https://query.yahooapis.com/v1/public/yql?q=select" 
      + "* from csv where url='" + url + "?'" 
      + "&format=json&diagnostics=true&callback=?")
    .then(function (data, textStatus, jqxhr) {
        var arr = [];
        var len = data.query.count;
        $.each(data.query.results.row, function (k, v) {
            $.map(v, function (val) {
                if (val === null) {
                    val = '""';
                };
                arr.push(val)
            });    
        });

        var rebuild_csv = function () {
            $.when(
              $("pre")
              .append(
                arr.splice(0, len).join(",") + "\r\n"))
            .done(function () {
                if (arr.length) {
                    rebuild_csv()
                };
            });
        };
        rebuild_csv();

    }, function (jqxhr, textStatus, errorThrown) {
        console.log(textStatus, errorThrown)
    });
});

jsfiddle http://jsfiddle.net/guest271314/2oLmxb0g/

See , also How to get attachment file content with jQuery

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177
1

Without FileReader API support, you cannot read the file locally. You have to resort to Activex scripting as @Donal suggests, or use Flash/Java based solutions which come with their own set of problems.

Alternatively, you can switch to a server-side based solution. The server side solution consists of posting the file to a server side API which can then parse the file and send back the content. You can wrap this with AJAX/iFrame based approach to make it happen behind the scenes without the user noticing anything.

You can build it from scratch (DIY) or use a solution like filepicker.io which does that for you.

Reading local files

so you could call filepicker.read() and get the contents of the file directly. In newer browsers we wrap the HTML5 File API, but in IE8 we’re not so fortunate.

Instead, we have our server read the file and send it back in a readable format. We use the procedure above to send the file to our server. Iframe, new form, and all. Then have the server read the contents, convert to base64 if needed, and send it back down to the client.

DIY version:

// grab your file object from a file input
$('#fileInput').change(function () {
  uploadFile(this.files[0]);
});

function uploadFile(file) {
  $.ajax({
    type: 'post',
    url: '/csvProcessorUrl?file=' + file.fileName,
    data: file,
    processData: false,
    contentType: 'text/csv'
  })
  .done(function(csvData) {
      // process csv data
  });
}

Note: csvProcessorUrl is just a dummy name I made up for the actual server side endpoint. Do replace it with proper one.

Community
  • 1
  • 1
Mrchief
  • 75,126
  • 20
  • 142
  • 189
0

You can use a third party library like: http://blog.filepicker.io/post/33906205133/hacking-a-file-api-onto-ie8

If not with IE8, IE9 you will have to use: ActiveXObject("Scripting.FileSystemObject");

For example:

var fso = new ActiveXObject("Scripting.FileSystemObject");

f = fso.OpenTextFile("c:\\foobar.txt", 1);

while (!f.AtEndOfStream)
{
    var line = f.ReadLine();
    // do stuff
}

f.Close();

Please Note (taken from here):

ActiveX objects may present security issues. To use the ActiveXObject, you may need to adjust security settings in Internet Explorer for the relevant security zone. For example, for the Local intranet zone, you typically need to change a custom setting to "Initialize and script ActiveX controls not marked as safe for scripting."

IE 10+ has a FileReader.

Donal
  • 31,121
  • 10
  • 63
  • 72
  • Thanks I tried ActiveXObject i do get "Automation Server cant create object" error also i need to change the Security Setting on it. – user428747 Sep 05 '14 at 19:50
  • @user428747 Yes, you need to enable it in your IE settings. Go to Tools, Internet Options, Security (Select the appropriate Zone), select Custom Level choose enable 'Initialize and script ActiveX controls not marked as safe for scripting' – Donal Sep 05 '14 at 19:55
  • I do not want to change the Internet Security settings on Client Machine hence i m trying to look for an alternative solution. As mentioned earlier unfortunately FileAPI does not support IE 8/9 so i need to take an alternate route – user428747 Sep 05 '14 at 20:03
  • Why do you think it's possible with IE8/9 without adjusting security permissions? I think you're stuck between a rock and hard place. – Bryan Boettcher Sep 10 '14 at 20:39
  • My requirements do not allow me to change client browser security settings. Yeah I am absolutely stuck. however i am looking in FileUpload.js option which has not been very helpful though. – user428747 Sep 12 '14 at 15:56
  • @user428747 Have you tried this: http://blog.filepicker.io/post/33906205133/hacking-a-file-api-onto-ie8 – Donal Sep 12 '14 at 16:00