How to make a button a file upload button with JavaScript?

Sometimes, we want to make a button a file upload button with JavaScript.

In this article, we’ll look at how to make a button a file upload button with JavaScript.

How to make a button a file upload button with JavaScript?

To make a button a file upload button with JavaScript, we can create a hidden file input.

And then we add a button that opens the hidden file input when we click it.

For instance, we write:

<input id='fileid' type='file' hidden/>
<input id='buttonid' type='button' value='Upload MB' />

to add the hidden file input and a button.

Then we write:

const openDialog = () => {
  document.getElementById('fileid').click();
}

document.getElementById('buttonid').addEventListener('click', openDialog);

to add the openDialog function to select the hidden file input and call click on it to open the file selection dialog.

Then we select the button and call addEventListener on it to add openDialog as a click listener.

Conclusion

To make a button a file upload button with JavaScript, we can create a hidden file input.

And then we add a button that opens the hidden file input when we click it.