Angular File Input

In this tutorial, I show you how to create an AngularJS 1.5.x directive to get file input from the user and use the data to display the data back to them.

Use Case

Throughout our use of Angular and web development in general, we find ourselves in just about every application needing some sort of file input from the user. Most of the time for me, this consists of the user uploading a profile image. Sometimes, throughout our application, we just want to quickly grab the data that a user uploaded and display it back to them. For example, they might want to know how their profile picture will look once uploaded without actually submitting the form. There are many use cases for this, but let’s move on.

A good practice I like to do is write out a few lines of english and then implement my code based on those comments. Shoutout to @jeffrey_way .

In English

//When the user clicks a button

// Open the file input

// When they select the file

// Get the data

//Display the data

Step 1:

In order to trigger a real file input, we have to add an element at the top of our body tag which we can use to get file input. Something like this

// ng-hide is there to hide the element
// we can't use type hidden because we need it to be a file chooser
<input id="fileInput" type="file" class="ng-hide"/>

Step 2:

Next, we need to make a directive to trigger the file input click.

// now all you need to do is bind the image source
// viola, image is showing
<button file-choose="imgSrc"></button>
<img ng-src="{{ imgSrc }}"/>

Final Thoughts

This directive and it’s concept has been tremendously helpful on many websites. This is a small example shown to just get the image source, but it can go so much further than that. I’ve personally done image cropping and other manipulations using the FileReader API with Angular. If you’ve done anything similar, please feel free to share with me on Twitter @b_ez_man