Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload and read text/csv file without submitting?

I have this form and I would like to read the uploaded file and then fill out the form using this read information without refreshing the page.

For example the first word might be "Bob" and so I would want that to go in my input text "First_name." I've been trying to searching online for a way to do this using JQuery or Ajax but I can't seem to find a solution.

Can this be done using the two methods previously mentioned? If so and if not can someone point me to a link or to where I can learn how to do this? The instances I have found include where one uses JQuery to upload the file and display the size without refresh (which is not exactly what I want).

I have also found how one can use an iFrame but this again is not what I want. I suppose I could always just submit the part of the page containing the textfile related information and show the same form but with the filled out information. But I feel as if this is kind of sloppy and I want to know if there is a better way.

Thanks.

like image 452
xereo Avatar asked Jun 24 '11 17:06

xereo


1 Answers

Firefox has a method to do this, the File and FileList API provide a way to get at the files selected by a file input element and have a text retrieval method.

A very basic example:

NB. Not all browsers support this code.

[I think Chrome, Firefox and Opera do at time of writing.]

HTML:

<form>
    <input type="file" name="thefile" id="thefile" />
</form>

<div id="text"></div>

JS (using jQuery):

$(document).ready(function() {
    $('#thefile').change(function(e) {
        if (e.target.files != undefined) {
            var reader = new FileReader();

            reader.onload = function(e) {
                $('#text').text(e.target.result);
            };

            reader.readAsText(e.target.files.item(0));
        }

        return false;
    });
});

Demo: http://jsfiddle.net/FSc8y/2/

If the selected file was a CSV file, you could then process it directly in javascript.

.split() will be useful in that case to split lines and then fields.

like image 119
Orbling Avatar answered Nov 12 '22 19:11

Orbling