Html file picker with jQuery

hakan picture hakan · Jun 12, 2012 · Viewed 26.1k times · Source

Possible Duplicate:
Reading client side text file using Javascript

I want to open a txt file at client, parse it with javascript and post parsed data to a server page with ajax. I have scripts for parsing and posting. All i need now is to simply pick file from client computer.

What I need is something like this:

<div id="content">
     <button id="selectFile" onclick="return selectFileClick();" />
</div>

When user clicks button, a file dialog box appears and returns selected file. With this file name, I will make other operations like parsing etc.

function selectFileClick()
{
    var fileName = filedialog();
    // parsing file...
    return false;
}

Edit: I dont want to upload file and I have a custom design which doesnt look like;

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

I need something like this: jquery file dialog plugin

Edit (2): I solved issue by this way;

$(function () {
    $("#button1").click(function (event) {
        event.preventDefault();
        $('#file').trigger('click');
    });

    document.getElementById('file').addEventListener('change', readFile, false);
});

at html;

<input id="button1" type="submit" value="add" />
<input type="file" id="file" style="display: none">

I hope this helps someone else ;)

Answer

phenomnomnominal picture phenomnomnominal · Jun 12, 2012

Have a look at this: HTML File API

That would probably be the easiest way to do it, e.g.

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

Then just attach a function to the "onChange" function of the element.

EDIT: Just noticed that you're using jQuery, so you could really just do:

$("#file").change(function() { selectFileClick(); });