Html file picker with jQuery [duplicate]
Asked Answered
T

1

6

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 ;)

Thetic answered 12/6, 2012 at 13:3 Comment(1)
#4951067 might help.Parthenogenesis
L
5

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(); });
Lethargy answered 12/6, 2012 at 13:14 Comment(1)
<input type="file" id="file"> is not always the best option. The browsers currently have hard-coded the text, and it is no way you can change it. Can be "changed" (workaround) by putting in an overlay image or styled box on top of it.Teapot

© 2022 - 2024 — McMap. All rights reserved.