views:

109

answers:

4

I want to make an "Open File" button to import txt files contents into a textarea.

How can I read the file contents without uploading it to the server?

I want to use javascript (with jquery lib) and I want to do it without refreshing the page.

+2  A: 

This isn't possible with vanilla javascript, you'd need flash or some other approach to do what you want.

The reasoning is security: to prevent you from reading allMyPasswords.txt :)

Nick Craver
+1  A: 

You can't.

File open dialog is opened by the browser in response to a FORM submit with an INPUT tag with the FILE type. The file has to be first uploaded to the server.

kervin
+1  A: 

I think I will do a simple ajax form to upload the file and then get the content with php before deleting the file and printing it, can't think of another solution.

Sebastian
A: 

As you say there's no other way than taking the text on the round trip to the server and back. However to ease the pain a bit you can fully automate this:

  1. enclose the file-upload input in a form tag of its own and give the form an id
  2. add an invisible iframe to your page and give it a name and use the same for the id
  3. use the iframes name as the target attribute of the form that holds the file upload
  4. bind a function to the file upload's change event to trigger the form's submit. this way as soon as you select your file and the file open dialog closes, the upload process begins
  5. as you set the target to the iframe the response from the server will arrive there, so have your php script send back something like the followin:

    echo "<script>window.top.window.file_ready('$file');</script>";

  6. write a js function called file_ready which takes the filename as a parameter and updates the value of your textarea by making an ajax call to the server.

Attribution is due. I learned this technique from AJAX file upload tutorial.

Majid