如何将本地文本文件上传到textarea(在网页内) [英] How to upload a local text file to a textarea (inside the webpage)
问题描述
我是一名新手程序员,需要一些帮助,找出如何将本地文本文件上传到我正在构建的网站内的文本区域。我非常流利的HTML / CSS,我对Javascript / JQuery有很好的了解,我只是在学习PHP。你能给予的任何帮助我都会非常感激。我有一个type =file和name =file的输入,我有一个带有.textbox类的textarea,我有一个运行Upload()函数的按钮这是我的javascript site。
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);
}
提前致谢!
推荐答案
实现FileReader的现代浏览器可以做到这一点。要测试你的浏览器,请检查是否定义了window.FileReader。
Modern browsers implementing FileReader can do this. To test your browser check if window.FileReader is defined.
这是我几天前写的一些代码。在我的例子中,我只需将文件拖到HTML元素上,该元素在此处引用为panel.in1,但您也可以使用(参见下面的参考资料)。
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);
}
这是reader.onloadend函数,它获取你的文件的文本在事件处理程序中恢复为this.result。
It is the reader.onloadend function which gets the text of the file which you recover in the event handler as this.result.
我从MDN获得了大部分关于如何执行此操作的机制: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
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.
这是我对类似问题的回答:使用javascript获取文本文件内容
This is my answer to the similar question : Get text file content using javascript
这篇关于如何将本地文本文件上传到textarea(在网页内)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!