HTML5 拖放:使用 JavaScript 在文本框中加载文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11313414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:43:28  来源:igfitidea点击:

HTML5 Drag and Drop: Load text file in a textbox with JavaScript

javascripthtml

提问by Akshat Mittal

I want to allow users to drag and drop (or select) a file from their computer and load it into a textbox with JavaScript.

我希望允许用户从他们的计算机拖放(或选择)一个文件,然后使用 JavaScript 将其加载到文本框中。

Is it possible to load a local file with JavaScript into a textbox? If yes, then how?

是否可以使用 JavaScript 将本地文件加载到文本框中?如果是,那么如何?

回答by Jim Schubert

I think everything you would want for HTML5 is included in remy/html5demoson github.

我认为您想要的 HTML5 的所有内容都包含在github 上的remy/html5demos中。

As an example, I modified http://html5demos.com/file-apito accept text files and display them in the browser.

例如,我修改了http://html5demos.com/file-api以接受文本文件并在浏览器中显示它们。

See the jsfiddle.

请参阅jsfiddle

Edit
Relevant script:

编辑
相关脚本:

// modified from http://html5demos.com/file-api
var holder = document.getElementById('holder'),
    state = document.getElementById('status');

if (typeof window.FileReader === 'undefined') {
    state.className = 'fail';
} else {
    state.className = 'success';
    state.innerHTML = 'File API & FileReader available';
}

holder.ondragover = function() {
    this.className = 'hover';
    return false;
};
holder.ondragend = function() {
    this.className = '';
    return false;
};
holder.ondrop = function(e) {
    this.className = '';
    e.preventDefault();

    var file = e.dataTransfer.files[0],
        reader = new FileReader();
    reader.onload = function(event) {
        console.log(event.target);
        holder.innerText = event.target.result;
    };
    console.log(file);
    reader.readAsText(file);

    return false;
};?

回答by Samuel Parkinson

Check out the HTML5 File API: http://www.html5rocks.com/en/tutorials/file/dndfiles/

查看HTML5 File APIhttp: //www.html5rocks.com/en/tutorials/file/dndfiles/

The spec also has a good example to get an idea of how it works:

规范也有一个很好的例子来了解它是如何工作的:

http://dev.w3.org/2006/webapi/FileAPI/#introduction

http://dev.w3.org/2006/webapi/FileAPI/#introduction