简体   繁体   中英

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/ .

<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();? 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

You can simply use this variable to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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