Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use html5 to input a local file and output the file on screen? [closed]

I'm trying to get a grip on the file API in HTML5 for accessing local files in a browser. I found some other SO questions about this and even found a nice guide here for choosing files locally.

However, I really need to be able to access text files this way and print them on screen, like in a textarea element. Does anyone know how this is done? As an example, I would like to read in a flat text file with a single line of text and print the contents in a textarea.

Thanks for the help!

like image 855
jake9115 Avatar asked Dec 20 '25 09:12

jake9115


1 Answers

Try this

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Any Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">


</head>
<body>

<input type="file" id="files" name="file" /> Read bytes: 
<textarea id="output"></textarea>

<script>
    function handleFileSelect(evt) {
        var files = document.getElementById('files').files;
        if (!files.length) {
          alert('Please select a file!');
          return;
        }

        var file = files[0];
        var reader = new FileReader();
        reader.onloadend = function(evt) {
            if (evt.target.readyState == FileReader.DONE) { // DONE == 2
                document.getElementById('output').textContent = evt.target.result;
            }  
        };
        reader.readAsText(file, "UTF-8");
    }


document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
like image 177
Cary Avatar answered Dec 22 '25 23:12

Cary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!