Reputation:
I am a novice programmer, and need some help figuring out how to upload a local text file to a textarea inside a website I'm building. I am very fluent in HTML/CSS, I have a decent knowledge of Javascript/JQuery, and I am just learning PHP. Any help you can give I would greatly appreciate. I have an input with type="file" and name="file" and I have a textarea with a class of ".textbox", and I have a button that runs the function "Upload()" Here is the javascript for my site.
var localfile = $("input[name=textfile]").val();
function Upload(){
$(".textbox").append(file);
}
Thanks in advance!
Upvotes: 4
Views: 4108
Reputation: 16053
Modern browsers implementing FileReader can do this. To test your browser check if window.FileReader is defined.
Here is some code I wrote a few days ago to do just this. In my case I simply drag a file onto the HTML element which is here referenced as panel.in1 but you can also use (see the reference below).
if (window.FileReader) {
function dragEvent (ev) {
ev.stopPropagation ();
ev.preventDefault ();
if (ev.type == 'drop') {
var reader = new FileReader ();
reader.onloadend = function (ev) { panel.in1.value += this.result; };
reader.readAsText (ev.dataTransfer.files[0]);
}
}
panel.in1.addEventListener ('dragenter', dragEvent, false);
panel.in1.addEventListener ('dragover', dragEvent, false);
panel.in1.addEventListener ('drop', dragEvent, false);
}
It is the reader.onloadend function which gets the text of the file which you recover in the event handler as this.result.
I got most of the mechanism on how to do this from MDN : https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
This code shows the basics of reading the file, the file itself is dragged into the text area, a nicer interface, I think, than having to go through the select file mechanisms, but those work equally well to select the file to read.
This is my answer to the similar question : Get text file content using javascript
Upvotes: 3
Reputation: 323
I think it will be good to
upload the file using iframe which gives you a ajax like user experience is what Gmail doing,
and then read the contents of the file using php
then send the contents back through ajax then append to textarea using js.
Does this makes sense?
Upvotes: -1