LearnReading Files Using The HTML5 FileReader API

   
Avatar

Matt West
writes on September 17, 2013

HTML5 saw the introduction of a number of new APIs that can be used to handle files in the browser. These APIs make it much easier to accomplish tasks like reading and writing files or uploading a file created using JavaScript.

In this blog post you are going to learn how to use the FileReader API to read the contents of a file from your local hard drive. You will be creating two demo applications. The first application will handle reading and then displaying the contents of a text file. The second will read an image file and then generate a data URL that will be used to display the image on the page.

Let’s get going!

Free trial on Treehouse: Do you want to learn more about HTML5? Click here to try 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 code shows how to create a new instance 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-8 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 result property of our FileReader instance to get the file’s contents. You will need to use this same approach for all of the read methods provided by FileReader.

var reader = new FileReader();

reader.onload = function(e) {
  var text = reader.result;
}

reader.readAsText(file, encoding);

readAsDataURL()

The readAsDataURL() method takes in a File or Blob and produces a data URL. This is basically a base64 encoded string of the file data. You can use this data URL for things like setting the src property for an image. We will look at how to do this later in the images demo.

var reader = new FileReader();

reader.onload = function(e) {
  var dataURL = reader.result;
}

reader.readAsDataURL(file);

readAsBinaryString()

The readAsBinaryString() method can be used to read any type of file. The method returns the raw binary data from the file. If you use readAsBinaryString() along 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 Blob or File object and produce an ArrayBuffer. An ArrayBuffer is a fixed-length binary data buffer. They can come in handy when manipulating files (like converting a JPEG image to PNG).

var reader = new FileReader();

reader.onload = function(e) {
  var arrayBuffer = reader.result;
}

reader.readAsArrayBuffer(file);

abort()

The abort() method will stop a read operation. This can come in handy when reading large files.

reader.abort();

Now that you have an understanding of how the FileReader API works lets take a look at a couple of examples.

Example: Reading Text Files With The FileReader API

Reading Text Files With The FileReader API

Reading Text Files With The FileReader API

See the Demo Download The Code View on CodePen

In this section you are going to learn how to build a small JavaScript application that reads a text file and displays it’s contents within a <pre> element.

To get started we first need to setup the HTML for our demo. We are going to use a file <input> to handle selecting our file but you could also use drag and drop. We also need to add a <pre> element that will be used for displaying the file’s contents.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>File API</title>

  <link rel="stylesheet" href="style.css">
</head>
<body>
  <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’s time to start writing the JavaScript code for your application. Create a new file called text.js to house this code.

First we need to get references to the important elements within our HTML. Here we get references to the file <input> and the <pre> element and store them in variables called fileInput and fileDisplayArea. We also setup an event listener on the fileInput that listens for the change event. This will be fired whenever the user selects a file.

window.onload = function() {
    var fileInput = document.getElementById('fileInput');
    var fileDisplayArea = document.getElementById('fileDisplayArea');

    fileInput.addEventListener('change', function(e) {
      // Put the rest of the demo code here.
    });
}

Now we need to write the code that will handle reading the text file. We first fetch the first file from our input by examining the fileInputs files property and store this in a variable called file. We then create another variable called textType that holds a regular expression that we will 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 we first check to make sure that the selected file is a text file by testing it’s 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 type is correct we create a new instance of FileReader. Next we setup an event listener for the onload event. Within this event listener we add some code that will update the innerText property of fileDisplayArea using the result property from our FileReader.

Finally we call the readAsText() method, passing in the file variable that we created earlier.

if (file.type.match(textType)) {
  var reader = new FileReader();

  reader.onload = function(e) {
    fileDisplayArea.innerText = reader.result;
  }

  reader.readAsText(file);  
} else {
  fileDisplayArea.innerText = "File not supported!";
}

If you load up the live demo you should be able to select a file from your local hard drive and see it’s contents displayed on the page.

Example: Reading Image Files With The FileReader API

Reading Image Files With The FileReader API

Reading Image Files With The FileReader API

See the Demo Download The Code View on CodePen

For our next demo we are going to create an application that reads an image file and then displays that image on the page. 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 also changed to images.js.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>File API</title>

  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id="page-wrapper">

    <h1>Image 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 as before. We get references to the key elements in our HTML and then setup an event listener for the file <input>.

window.onload = function() {
    var fileInput = document.getElementById('fileInput');
    var fileDisplayArea = document.getElementById('fileDisplayArea');

    fileInput.addEventListener('change', function(e) {
      // Put the rest of the demo code here.
    });
}

Next we start by fetching the first file from fileInput. We then create the regular expression for checking the file type. This time we want an image file so the regular expression is: /image.*/.

As before, we do a check to make sure that the selected file is indeed an image.

We’re now at the point where things start to get a little different. We start by creating a new instance of FileReader and then setting up an event listener for the onload event.

When this event listener is called we first need to clear out fileDisplayArea just in case there is already an image in there. We can do this by setting fileDisplayArea.innerHTML to an empty string.

Next we create a new Image instance and set it’s src property to the data URL that is generated by readAsDataURL(). Remember, the data URL can be accessed from the FileReader‘s result property. We then add 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 = /image.*/;

if (file.type.match(imageType)) {
  var reader = new FileReader();

  reader.onload = function(e) {
    fileDisplayArea.innerHTML = "";

    // Create a new image.
    var img = new Image();
    // Set the img src property using the data URL.
    img.src = reader.result;

    // Add the image to the page.
    fileDisplayArea.appendChild(img);
  }

  reader.readAsDataURL(file); 
} else {
  fileDisplayArea.innerHTML = "File not supported!";
}

Load up the live demo and select a file from your hard drive. You should see that the file is display on the page. If you were to use the browser’s developer tools to examine the <img> element you would see that the src attribute has been set using the data URL for the image you selected.

Browser Support 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. It’s worth noting that Internet Explorer only started supporting FileReader in IE10.

IE Firefox Chrome Safari Opera
10+ 3.6+ 6.0+ 6.0+ 11.1+

Source: http://caniuse.com/filereader

Final Thoughts

Historically there has been a big divide between the capabilities of a native app and that of an application built with pure web technologies. Whilst I don’t deny that this gap still exists, APIs like FileReader are really helping to close up the divide.

In this post you have learned how to use the FileReader API to read a file from the user’s hard drive and display it’s contents on the page. If you feel like a challenge why not try to create an application that allows the user to drop a file onto the page rather than using an <input> element. My previous post on implementing native drag and drop should help to get you started.

GET STARTED NOW

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started

36 Responses to “Reading Files Using The HTML5 FileReader API”

  1. David Ranney on September 8, 2016 at 4:26 pm said:

    A very well written article. Your examples were simple enough to not distract from the technique you were demonstrating, but not so simple as to not be useful.

    Your explanations were complete yet concise.

    I love this kind of documentation!

  2. Is it possible to read a local csv file directly from a folder (the same folder as the main html page) instead of the upload functionality?

  3. 業界最高峰のブランドコピー 激安、コピーブランド、スーパーコピーブランド(N級品)通販専門店!ブランドコピー,コピーブランド,スーパーコピーブランド,ブランドコピー 激安,偽物ブランド、偽物のバッグ、腕時計、財布など激安で買える!全部のスーパーコピー販売品物のなかで私達のブランド激安が一番有名です http://www.msnbrand.com/brand-copy-IP-24.html

  4. スーパーコピーブランド 代引き安心老舗当店は海外高品質のブランドコピー 代引き,スーパーコピー 代引き通販人気老舗です。2015新作 ルイヴィトン コピー代引き、シャネル コピー代引き、 http://www.ooobag.com/index.html

  5. 100%実物写真ですし、品質が完璧です!”スーパーコピーブランド財布激安 偽物財布激安コピー ルイヴィトン財布偽物,偽物財布コピーエルバーキンコピースーパーコピー財布ブランド財布コピーブランドコピー激安バレンシアガ スーパーコピー激安ロレックス スーパーコピー時計ブランド財布激安 偽物財布激安コピー ルイヴィトン財布偽物,偽物財布コピーブランド激安市場-jck35販売:ブランド財布コピー,激安ブランド,財布コピー,偽ブランド,偽 ブランド財布,偽物ブランド財布,ブランドコピー,ヴィトンコピー,ルイヴィトン財布偽物, シャネル財布コピー,グッチ財布コピー,エルメス財布偽物,D&G 財布コピー,ボッテガ 財布 .2013年新作スーパーコピーロレックス,スーパーコピーロレックス時計通販スーパー コピー品その他の世界一流ロレックススーパーコピー時計品を扱っています。 ホームページをクリックして商品をご覧下さい.ロレックスコピー,業界No.1人気スーパーコピーロレックス腕時計専門販売ロレックスコピー(ROLEXスーパーコピー)のロレックス レプリカ販売専門店です。すべての商品は品質2年無料保証です,ロレックス デイトジャスト 偽物,人気満点ロレックス コピーn級品新作大特集 http://www.eevance.com/index.html

  6. ブランドコピーの専門店スーパーコピー豊富に揃えております、最も手頃ず価格だお気に入りの商品を購入。弊社フクショー(FUKUSHOW)ブランド腕時計、雑貨、小物最新作!エルメス バーキンスーパーコピー時計N品のみ取り扱っていまずのて、2年品質保証。エルメス食器,スーパーコピーブランド激安販売シャネル 財布スーパーコピー,スーパーコピーブランド 財布激安販売エルメス スーパーコピー,スーパーコピーブランド激安販売売スーパーコピーロレックス スーパーコピー,スーパーコピーROLEX激安販売IWC スーパーコピー,スーパーコピーIWC時計激安販売エルメス時計スーパーコピー,スーパーコピーhermes時計激安販売ボッテガ ヴェネタスーパーコピー,スーパーコピーブランド財布激安販売スーパーコピー時計スーパーコピーブランドバッグ時計コピー激安販売 http://www.newkakaku.net/guz1.htm

  7. スーパーコピー腕時計,ロレックスコピー,ブライトリングコピー,ボーム&メルシエコピー時計コピー業界最高峰スーパーコピー時計通販専門!7年以上の販売実績を 持つ時計コピー老舗!時計コピーであれば何でも揃えられます コピー時計 時計スーパーコピー通販専門店!時計コピー時計販売通販! コピー時計スーパー コピー等の 最高級のレプリカコピー時計を販売ロレックスコピー,ガガミラノコピー ,IWCコピー ,オメガコピー ,フェラーリコピー ,フランクミュラーコピー ,ベル&ロスコピー ,各種のブランドはコピーを表しますコピーを表して、時計をコピーして、スーパーコピーは代 金引換払いにして、スーパーはブランドをコピーして、スー パーは時計をコピーして代金引換払いにして、スーパーは時 計をコピーして、スーパーは腕時計をコピーして、ブランド はスーパーマーケットを表してコピーして、ブランドのスー パーマーケットはコピーして、ブランドはコピーを表して、 腕時計はコピーします ,ボーム&メルシエコピー時計コピー業界最高峰スーパーコピー時計通販専門!7年以上の販売実績を 持つ時計コピー老舗!時計コピーであれば何でも揃えられます コピー時計 時計スーパーコピー通販専門店!時計コピー時計販売通販! コピー時計スーパー コピー等の 最高級のレプリカコピー時計を販売ロレックスコピー,ガガミラノコピー ,IWCコピー ,オメガコピー ,フェラーリコピー ,フランクミュラーコピー ,ベル&ロスコピー ,各種のブランドはコピーを表しますコピーを表して、時計をコピーして、スーパーコピーは代 金引換払いにして、スーパーはブランドをコピーして、スー パーは時計をコピーして代金引換払いにして、スーパーは時 計をコピーして、スーパーは腕時計をコピーして、ブランド はスーパーマーケットを表してコピーして、ブランドのスー パーマーケットはコピーして、ブランドはコピーを表して、 腕時計はコピーします http://www.wtobrand.com/he1.html

  8. BVLGARI(バッグ?財布?小物)CHLOE(バッグ?財布、小物)偽物ブランド,激安,コピー?ルイヴィトンバッグ,偽物?ルイヴィトン財布,コピーバッグ,ブランドバッグ,偽物バッグ,偽物シャネルバッグ,偽物エルメスバッグ,偽物グッチバッグ,偽物財布,コピー財布,時計の專門店 http://www.msnbrand.com/brand-copy-IP-12.html

  9. スーパーコピーブランド弊社は安心と信頼のスーパーコピーブランド (N級品)専門店です!全国送料無料!日本一流品質のスーパーコピー時計、ブランド財布コピー、ブランドバッグコピー新作最新入荷!ロレックススーパーコピー,ウブロ スーパーコピー,ブランド時計 コピー,ブランド スーパーコピー,コピーブランド 通販,スーパーコピー 財布その他の世界一流ブランドコピーを取り扱っています。商品は全て最高な材料と優れた技術で造られて、正規と比べて、品質が無差別です!人気時計コピー、N級ブランドコピーのお求めはぜひ当店へ。弊社は正規品と同等品質のブランドコピー品を低価でお客様に提供します
    エルメス ボリードスーパーコピー.ブランド直営店.ブランド,エルメス激安通販,業界で最高な品質に挑戦します!”ブランドN級品ブランドコピー 代引き,スーパーコピー時計,ブランドN級品,楽天コピーブランド,,偽物ブラン日本最大級の最高のスーパーコピーブランド財布激安代引き販売店,スーパーコピー時計の激安老舗.!国内No.1時計コピー工房,アフターサービスも自ら製造したスーパーコピー時計なので、技術力でお客様に安心のサポー トをご提供させて頂きます。スーパーコピー 代引きN品をご 購入の方は、こちらへ.弊社は正規品と同等品質のコピー品を低価で お客様に提供します!すべての商品は品質2年無料保証です。100%実物写真ですし、品質が完璧です!”スーパーコピーブランド財布激安 偽物財布激安コピー ルイヴィトン財布偽物,偽物財布コピー http://www.brandiwc.com/brand-3-copy-0.html

  10. スーパーコピーブランドショップ有名ブランド品の輸入業、卸売り業、インターネット小売販売N級,,S級 ヴィトン、シャネル、グッチ、財布、バッグ。 高級腕時計ROLEX 、OMEGA 、CARTIER 、 BVLGARI、是非ご覧下さい。2015超人気腕時計、LOUIS VUITTON新品の大量入荷!商品の数量は多い、品質はよい、価格は低い、現物写真!本当の意味でのハイレプがほしい方にお勧めです。経営方針: 品質を重視、納期も厳守、信用第一は当社の方針です。
    スーパーコピー商品、ブランドコピ ー財布、偽物バッグコピー財布コピーN 級品、ブ ランドスーパーコピー商 品、グッチ財布コピー,ミュウミュウ 財布激安。ブランドスーパーコ ピー銀座、ランドスーパーコピー財布。ブラ ンドスーパーコピー代引き、ブランドスーパーコピー専門店、ご購入する度、ご安心とご満足の届けることを旨にしておりますよろしくお願いします ありがとうございます http://www.ooobag.com/index.html

  11. スーパーは時計をコピーしますブランド偽物、偽物ブランド、ルイヴィトンコピー、 ロレックスコピー、シャネルコピー、グッチコピー、エルメスコピー、 ボッテガヴェネタコピー、 バーバリーコピー、ミュウミュウコピー、トリーバーチコピー、バレンシアガコピー、ディオールコピー、ブルガリコピー、ブラダコピー、 ドルチェ&ガッバーナコピー、オメガコピー、フランク ミュラーコピー、gagaコピー。古驰拷贝, 靴/サンダル,サングラスコピー
    エルバーキンコピーエルメスバーキン30コピーエルメス ボリード47,エルメス バッグ 名前,エルメス ネクタイ ピンク エルメス クラッチバッグ,エルメス バッグ コピー,エルメス バーキン コピー エルメス 財布 ダミエ オークション,エルメス ヨーロッパ,エルメス エールライン エルメス クラッチ激安通販、高い品質、送料無料。バーキン25コピー、バーキン30コピー、バーキン35コピー、バーキン40コピーなど世界中有名なブランドレプリカを格安で通販しております。N級品スーパーコピーブランドは ブランドスーパーコピー超N品エルメスバッグ,エルメス バーキン25 , バーキン30.バーキン35.バーキン40. エルメス(HERMES) ケリー http://www.bestevance.com/Hermes-1/index.htm

  12. ブランドN級品ブランドコピー 代引き,スーパーコピー時計,ブランドN級品,楽天コピーブランド,,偽物ブラン日本最大級の最高のスーパーコピーブランド財布激安代引き販売店,スーパーコピー時計の激安老舗.!国内No.1時計コピー工房,アフターサービスも自ら製造したスーパーコピー時計なので、技術力でお客様に安心のサポー トをご提供させて頂きます。スーパーコピー 代引きN品をご 購入の方は、こちらへ.弊社は正規品と同等品質のコピー品を低価で お客様に提供します!すべての商品は品質2年無料保証です。
    高品質2015シャネル スーパーコピー激安專門店弊社は海外大好評を博くシャネル コピー激安老舗です,2015高品質シャネル バッグ コピー,シャネル 靴 コピー,シャネル 財布 コピー品の品質はよくて、激安の大特価でご提供します。 http://www.gowatchs.com/brand-208.html

  13. This doesn’t seem working in IE.
    Any idea why?
    Thank you.

  14. Dear,its upload .html extensions file as well.please verify it.

  15. What if I want to read local .txt file directly without the choose file button, what should I do?

    • You cannot directly access the user’s filesystem. You can only read files that are explicitly passed to your application through an interactive element such as a file input or drag and drop area.

      • jonathan on January 15, 2016 at 4:05 am said:

        I get that you cant access the harddrive, but what about a relative path? as when you load an image? seems like there has to be a way to read a file relative to the javascript file “locally”?

        • Well the JavaScript file is on the server, so no problem to read a file relative to that. The point is that you can only access files on the user’s system (which is what we’re referring to here as “local”) if the user has specifically selected them – for obvious security reasons.

  16. 1: var reader = new FileReader();
    2: reader.onload = function(e) {
    3: var dataURL = reader.result;
    4: }
    5: reader.readAsDataURL(file);

    Why doesn’t line 5 read: reader.readAsDataURL(dataURL) ??
    If your not using dataURL why reference it at all?

    If this method is changing the interpetation of the data I have already stored in dataURL can I call other methods after the fact?
    eg.

    var myBits = reader.result
    reader.readAsDataURL(file);
    doSomething with myBits

    reader.readAsArrayBuffer(file);
    doSomething different with myBits now that it has been transformed.

    Just seems like a terrible notation to move the file into a variable, and then perform actions on the “file” instead of the variable instead. if file=myVar couldn’t you call readAs on either of them?

  17. 1: var reader = new FileReader();
    2: reader.onload = function(e) {
    3: var dataURL = reader.result;
    4: }
    5: reader.readAsDataURL(file);

    This is very confusing. At line 3 what does the variable “dataUrl” hold? An arrayBuffer? or a base64?

    Is reader.readAsDataURL a function? does it have a return value? Does line 5 change the value of file? or dataURL or both. and if so wot!

    • the variable dataURL holds base64 and reader.readAsDataURL() is a method that returns base64 of input filelist object blob on October 26, 2017 at 3:41 am said:

      he variable dataURL holds base64 and reader.readAsDataURL() is a method that returns base64 of input filelist object blob

  18. shsweb.ru on October 2, 2013 at 4:25 am said:

    1. In Text reader html tag not closed
    2. Use .innerHTML instead of .innerText

  19. Jason X Bånd on October 1, 2013 at 11:29 pm said:

    how can I preserve the File object across browser restarts? My scenario is that when the user picks the file, the browser is offline. At some later time, the user goes online and I want to read the previously picked file to upload it to a server.

  20. Nguyen Truong Thin on October 1, 2013 at 10:19 pm said:

    This is a awesome feature in HTML5. But not support for IE9 🙁

  21. Guest1234 on September 30, 2013 at 2:45 am said:

    I want to display raw image data (YUV, RGB…). I can read it from a file using filereader with readAsArrayBuffer() API. But how do I display it? I am using Javascript and HTML along with NaCL and I’m a newbie in this.

  22. kaushik ray on September 23, 2013 at 3:14 pm said:

    How can we pass this value back to server..I am trying to do this for any type of file but not able to capture the data in blob in controller. ANy help???

  23. Some other docs that are pretty useful: http://www.javascripture.com/FileReader

  24. thanks so much. let find moments to meditate, relax is play game with me. it’s great to play the tai game ban ca an xu in the gioi giai tri mobi and Forget tired after working hard learning

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop