How to Read Text File in Html
HTML5 saw the introduction of a number of new APIs that tin can exist used to handle files in the browser. These APIs make information technology much easier to achieve tasks similar reading and writing files or uploading a file created using JavaScript.
In this blog postal service you are going to acquire how to use the FileReader API to read the contents of a file from your local hard drive. You will be creating 2 demo applications. The first application volition handle reading and then displaying the contents of a text file. The second will read an prototype file and then generate a data URL that volition be used to display the paradigm on the folio.
Let's get going!
Free trial on Treehouse: Practice you lot want to learn more about HTML5? Click here to endeavor a free trial on Treehouse.
The FileReader Interface
The FileReader interface provides a number of methods that can be used to read either File or Blob objects. These methods are all asynchronous which means that your program will not stall whilst a file is being read. This is particularly useful when dealing with large files.
The following lawmaking shows how to create a new example of FileReader.
var reader = new FileReader();
In the following sections we are going to take a look at the methods provided by FileReader.
readAsText()
The readAsText() method can be used to read text files. This method has two parameters. The first parameter is for the File or Blob object that is to be read. The second parameter is used to specify the encoding of the file. This second parameter is optional. If you don't specify an encoding UTF-viii is assumed by default.
As this is an asynchronous method we need to setup an event listener for when the file has finished loading. When the onload event is called we can examine the issue property of our FileReader instance to get the file'due south contents. You will demand to use this aforementioned approach for all of the read methods provided by FileReader.
var reader = new FileReader(); reader.onload = function(e) { var text = reader.consequence; } reader.readAsText(file, encoding); readAsDataURL()
The readAsDataURL() method takes in a File or Hulk and produces a data URL. This is basically a base64 encoded string of the file data. You can use this information URL for things like setting the src holding for an paradigm. We will look at how to do this subsequently in the images demo.
var reader = new FileReader(); reader.onload = part(e) { var dataURL = reader.consequence; } reader.readAsDataURL(file); readAsBinaryString()
The readAsBinaryString() method can exist used to read any type of file. The method returns the raw binary information from the file. If you use readAsBinaryString() forth with the XMLHttpRequest.sendAsBinary() method you can upload any file to a server using JavaScript.
var reader = new FileReader(); reader.onload = function(e) { var rawData = reader.result; } reader.readAsBinaryString(file); readAsArrayBuffer()
The readAsArrayBuffer() method will read a Hulk or File object and produce an ArrayBuffer. An ArrayBuffer is a stock-still-length binary information buffer. They can come in handy when manipulating files (like converting a JPEG epitome to PNG).
var reader = new FileReader(); reader.onload = office(e) { var arrayBuffer = reader.outcome; } reader.readAsArrayBuffer(file); abort()
The abort() method will stop a read operation. This can come up in handy when reading large files.
reader.arrest();
At present that you lot take an understanding of how the FileReader API works lets have a look at a couple of examples.
Example: Reading Text Files With The FileReader API
Reading Text Files With The FileReader API
See the Demo Download The Lawmaking View on CodePen
In this section you are going to learn how to build a small JavaScript awarding that reads a text file and displays it'south contents within a <pre> chemical element.
To get started we first need to setup the HTML for our demo. Nosotros are going to use a file <input> to handle selecting our file but y'all could also use drag and driblet. Nosotros also need to add a <pre> element that will be used for displaying the file'due south contents.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>File API</title> <link rel="stylesheet" href="mode.css"> </head> <trunk> <div id="page-wrapper"> <h1>Text File Reader</h1> <div> Select a text file: <input type="file" id="fileInput"> </div> <pre id="fileDisplayArea"></pre> </div> <script src="text.js"></script> </body> </html>
You can find a copy of the stylesheet used in this demo in the code resources.
Now it'south fourth dimension to first writing the JavaScript lawmaking for your application. Create a new file called text.js to house this code.
First nosotros need to get references to the important elements within our HTML. Here we become references to the file <input> and the <pre> element and store them in variables called fileInput and fileDisplayArea. We also setup an upshot listener on the fileInput that listens for the modify issue. This volition be fired whenever the user selects a file.
window.onload = function() { var fileInput = certificate.getElementById('fileInput'); var fileDisplayArea = document.getElementById('fileDisplayArea'); fileInput.addEventListener('change', function(e) { // Put the rest of the demo code here. }); } At present we need to write the code that will handle reading the text file. We first fetch the showtime file from our input by examining the fileInputs files belongings and store this in a variable called file. Nosotros and then create another variable called textType that holds a regular expression that we volition use later to test that the selected file is indeed a text file.
var file = fileInput.files[0]; var textType = /text.*/;
In this next block of code nosotros first check to make certain that the selected file is a text file by testing it'southward type property. If the file is not a text file we show a File not supported! message on the page.
Once we have determined that the file blazon is right we create a new instance of FileReader. Adjacent we setup an event listener for the onload event. Inside this event listener nosotros add together some code that will update the innerText property of fileDisplayArea using the result holding from our FileReader.
Finally we call the readAsText() method, passing in the file variable that we created earlier.
if (file.type.lucifer(textType)) { var reader = new FileReader(); reader.onload = office(eastward) { fileDisplayArea.innerText = reader.result; } reader.readAsText(file); } else { fileDisplayArea.innerText = "File non supported!"; } If y'all load up the live demo y'all should be able to select a file from your local difficult drive and see it'southward contents displayed on the page.
Example: Reading Paradigm Files With The FileReader API
Reading Image Files With The FileReader API
See the Demo Download The Code View on CodePen
For our adjacent demo we are going to create an application that reads an paradigm file and then displays that prototype on the folio. To do this we are going to be using the readAsDataURL() method.
The HTML markup for this demo is very similar to the HTML we used before. The main difference is that we are now using a <div> element as our fileDisplayArea rather than a <pre>. Note that the name of the JavaScript file has likewise changed to images.js.
<!DOCTYPE html> <html lang="en"> <caput> <meta charset="utf-viii"> <title>File API</title> <link rel="stylesheet" href="mode.css"> </head> <body> <div id="page-wrapper"> <h1>Epitome File Reader</h1> <div> Select an image file: <input type="file" id="fileInput"> </div> <div id="fileDisplayArea"></div> </div> <script src="images.js"></script> </body> </html>
The initial JavaScript code for this demo is exactly the same equally before. We become references to the primal elements in our HTML and then setup an event listener for the file <input>.
window.onload = function() { var fileInput = document.getElementById('fileInput'); var fileDisplayArea = certificate.getElementById('fileDisplayArea'); fileInput.addEventListener('alter', function(e) { // Put the balance of the demo lawmaking hither. }); } Next nosotros start by fetching the showtime file from fileInput. We then create the regular expression for checking the file type. This fourth dimension nosotros want an paradigm file so the regular expression is: /image.*/.
As before, nosotros practice a bank check to make certain that the selected file is indeed an prototype.
We're now at the point where things start to get a piffling dissimilar. We start by creating a new instance of FileReader and so setting up an event listener for the onload event.
When this event listener is called we showtime need to articulate out fileDisplayArea just in case there is already an epitome in at that place. Nosotros tin practice this by setting fileDisplayArea.innerHTML to an empty cord.
Next nosotros create a new Paradigm case and fix it's src belongings to the information URL that is generated by readAsDataURL(). Remember, the data URL tin can be accessed from the FileReader'southward result property. We then add together img to the fileDisplayArea using appendChild().
Finally we issue a call to readAsDataURL() and pass in the selected image file.
var file = fileInput.files[0]; var imageType = /prototype.*/; if (file.type.match(imageType)) { var reader = new FileReader(); reader.onload = function(e) { fileDisplayArea.innerHTML = ""; // Create a new image. var img = new Prototype(); // Set up the img src holding using the data URL. img.src = reader.issue; // Add the prototype to the page. fileDisplayArea.appendChild(img); } reader.readAsDataURL(file); } else { fileDisplayArea.innerHTML = "File not supported!"; } Load up the alive demo and select a file from your hard drive. You should run into that the file is display on the folio. If you were to use the browser'due south programmer tools to examine the <img> element you lot would run into that the src attribute has been fix using the data URL for the image yous selected.
Browser Back up for the FileReader API
Browser support for the FileReader API is pretty good. The API will work in the latest versions of all the major desktop browsers. Information technology's worth noting that Internet Explorer simply started supporting FileReader in IE10.
| IE | Firefox | Chrome | Safari | Opera |
|---|---|---|---|---|
| 10+ | three.vi+ | 6.0+ | 6.0+ | xi.i+ |
Source: http://caniuse.com/filereader
Terminal Thoughts
Historically at that place has been a big divide between the capabilities of a native app and that of an application built with pure spider web technologies. Whilst I don't deny that this gap even so exists, APIs similar FileReader are actually helping to shut upwardly the split.
In this mail service you have learned how to use the FileReader API to read a file from the user'south hard drive and display it's contents on the page. If you lot feel like a challenge why not try to create an application that allows the user to drop a file onto the folio rather than using an <input> element. My previous mail on implementing native drag and drop should help to get yous started.
Useful Links
- Can I Utilise… FileReader API
- FileReader Docs (MDN)
- File API Specification (W3C)
Want to learn more most Javascript?
Acquire how to use JavaScript to add interactivity to websites.
Learn more
Source: https://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
0 Response to "How to Read Text File in Html"
Post a Comment