Since HTML5 we’ve been allowed to use the File API which makes it possible for web content to ask the user to select local files and upload an image or a file back to the website. In this code sample we’ll learn how to make one of these buttons and as usual, it’s going to be pretty simple ?
Table of contents:
Let’s get started: How to make the button
All we’re going to need for this is the help of our <input> and <label> elements. We’ll use our type attribute on <input> element and set it to a ‘file’, we’ll also set an ‘id’ so that we can come back to this when we want to trigger the action. We’ll add a <label> element and think of accessibility while we’re building our features.
<label for='uploadFile'> Select a file: </label>
<input type='file' id='uploadFile' multiple>
This will now add a grey looking button with the text ‘choose file’ written within it’s borders. Once we’ve pressed the button we’ll be able to select items. Once selected, item’s name will appear where we’d normally be seeing ‘No file chosen’ text – and voila! We have a working button ?
Before we selected an image:
After we selected an image:
You might see we’ve added the ‘multiple’ attribute to our input element and in case you’re wondering what it does we’ll drop in a quote we got from MDN Web Docs which holds a lot more information on the topic:
The
multiple
attribute on theinput
element allows the user to select multiple files.
More info: How to access and show uploaded files
Here is where our no-javascript journey ends ? To add action behind these buttons we’ll need to use event listeners to know ‘when’ do we want action to happen.
We’ll need to ‘register’ which element is the one giving us the uploaded image and get all the files we’ve uploaded from it and at the end, we’ll have to access that information and display it back to the user.
There are multiple ways to do this and depending on your JavaScript preference of vanilla vs frameworks they might be very different. Because of this we’ll just go through accessing the first file on the list:
How to access the first selected file:
let selectedFile = document.getElementById('uploadFile').files[0];
Once we’ve got our selected file, we’ll need to add our ‘submit’ button in order to actually ‘upload’ our image to the server. If you’d like to learn more about uploading files/images and explore drag & drop feature, MDSN Web Docs will be super helpful in getting you there.