It seems to me that so often in our days as web developers we are swept this cool new framework or that fancy new library. In all of this it can be easy to look over some of the powerful abilities which we have built right into the spec of the technologies at the root of what we do. For this reason, I was particularly excited to learn just how easy the HTML5 spec makes it to upload and save files and thought I would share it here for anyone who might not know.
Jumping right to it the first thing we need to do is setup an input that accepts a file.
Simple, right? What if we wanted to allow multiple file uploads?
Yup, that’s it. The simple addition of the multiple tag will allow us to continue to upload multiple files from this one input tag. Alright so what about that ‘onchange’ function? Well every time a file is added via the input it fires a change event and that function will be called and passed the current array of files as a property. Let’s take a look.
Here I am displaying the ‘handleFiles’ function built to handle multiple files by iterating over each file in the array but you can handle a single file but simply referring to the first index. Let’s go ahead and walk through it one time.
On line thirteen we create a new ‘FileReader’ object which can asynchronously read files for us. Then on line 15 we setup the ‘onload’ function which will handle the file contents once reading has finished. At this point we can now grab the contents of the file from the event and except rather than the original file format we now have a base64 encoded string, which is awesome! Why? Because with a string we can now transmit this file wherever we want! Want to save a user profile image to your database? Go ahead and send that ‘POST’ request. Want to render it on the page? Pass it to the ‘src’ property of your image tag. That’s all there is to it.