简体   繁体   English

HTML5读取文件

[英]HTML5 Reading File

I am trying to develop an application where it allows the user to choose a file and then read it and display the text on the screen. 我正在尝试开发一个应用程序,它允许用户选择一个文件,然后阅读该文件并在屏幕上显示文本。

My code can be found here: http://jsfiddle.net/5sy076n5/1/ . 我的代码可以在这里找到: http : //jsfiddle.net/5sy076n5/1/

<html>
  <head>
    <title>FileReader Example</title>

    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

    <script type="text/javascript" charset="utf-8">



        function testRead() {

            var fileSelector = document.createElement('input');
            fileSelector.setAttribute('type', 'file');

            fileSelector.click();


        }

    </script>
      </head>
      <body>
        <h1>Example</h1>
        <p>Read <a onClick="testRead();">File</a></p>
      </body>
    </html>

You may notice that I don't have an input tag inside the body. 您可能会注意到,我体内没有输入标签。 This is because I want the user to click on the tag rather than the text. 这是因为我希望用户单击标签而不是文本。

My problem is what I am suppose to do after fileSector.click();? 我的问题是在fileSector.click();之后我应该做什么? How can I get what file was chosen? 如何获得选择的文件?

You have already created the input element on runtime and you have the reference of it fileSelector 您已经在运行时创建了input元素,并具有了它的引用fileSelector

You can simply use this variable to FileReader API 您可以简单地将此变量用于FileReader API

function testRead() {
    var fileSelector = document.createElement('input');

    fileSelector.setAttribute('type', 'file');

    fileSelector.click();

    fileSelector.addEventListener('change', function () {
        var file = fileSelector.files[0];

        var reader = new FileReader();
        reader.onload = function (e) {
            var text = reader.result;
            console.log(text);     // Select *.txt file and see console
        }

        reader.readAsText(file);
    });
}

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM