DEV Community

loading...
Cover image for How to create a custom file upload button

How to create a custom file upload button

faddalibrahim profile image Faddal Ibrahim ・2 min read

I find the default HTML file upload button rather ugly. Annoying enough, there seems to be no way to style it directly. Here is how I created a custom file upload button.

1. Use a label tag and point its for attribute to the id of the default HTML file upload button

<input type="file" id="actual-btn"/>
<label for="actual-btn">No file chosen</label>
Enter fullscreen mode Exit fullscreen mode

By doing this, clicking the label element in the browser toggles the default HTML file upload button (as though we clicked it directly).

The output of the above code is below. As you can see, we only have a Choose File text (from the label element) a few pixels to the right of the actual upload button.

We can click the Choose File text, and it will toggle the upload window (Click it and see)

2. Style the label element and hide the default HTML file upload button

We hide the default HTML file upload button in the browser by adding the hidden attribute to the tag like so

<input type="file" id="actual-btn" hidden/>
Enter fullscreen mode Exit fullscreen mode

Now we style the label element to look more like a button.

label {
  background-color: indigo;
  color: white;
  padding: 0.5rem;
  font-family: sans-serif;
  border-radius: 0.3rem;
  cursor: pointer;
  margin-top: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

Now we have this beautiful custom button, which actually works like the original file upload button:

At this point, we are done. But there is one more glitch to fix.

With the default file upload button, there is a no file chosen text beside the button (scroll up to the first codepen window), which gets replaced with the name of the file we will be uploading. Unfortunately, we don't get to see that with our custom button. How do we do that?

What I did was to include a span tag (with an id of file-chosen) right after our custom file upload button.

In the javascript file, I listen to the change event on the original file upload button(which we have hidden). A file object is returned which contains the details(such as name, file size etc) of the file uploaded.

Then I set the text content of the span element(with the id of file-chosen) to the name property of the file object returned. The final result is below. Test it out.

Kindly leave your comments and questions down below

Discussion

pic
Editor guide
Collapse
bugs_bunny profile image
Derek Oware

You can style the button with input::-webkit-file-upload-button. You can check the docs

Collapse
faddalibrahim profile image
Faddal Ibrahim Author

Interesting. Never knew about that. Thanks for sharing, Derek.

Collapse
vidhyanand profile image
Vidhyanandcs

I have checked the docs not much browser support

Collapse
vidhyanand profile image
Vidhyanandcs

was helpful. thanks