AngularJS File Directive

20 May 2014 angularjs, directive, file, and javascript

A common component in web applications is the form <input type="file">. To connect this input any kind of logic or just render a preview of the selected files tends to be a hassle involving a POST to some server-side code. For some cases it would be a lot easier containing parts of this on the client-side.

After implementing this for various angular projects a pretty useful directive started to emerge.


angular.module('myApp', ['file']);
<!-- Bind the values to $scope.files -->
<input type="file"

<!-- Render the selected files directly in the view -->
<div ng-repeat="file in files">
  <h4>{{ }}</h4>
  <img alt="{{ }}"
    ng-src="data:{{ file.type }};base64,{{ file.body }}">


  • {{ }}

    {{ }}

How it works

  • Listen for change in input element.
    • For each targeted file:
      1. Read the file as text or binary string.
      2. Base64 encode body if file type is binary string.
      3. Compile type, name & body.
      4. Apply new values to $scope when last file is done.


Install with Bower:

$ bower install angular-file-directive

Include from a RawGit’s CDN:

<script src="//"></script>

Or download manually.

The code

Please check it out on GitHub and submit any issues encountered.