(Jump to Code | Demo) When we design an application, we get the requirements to upload images, pdfs, videos and all other sorts of files. We do this using html input type="file"
of forms. But cases may arise where you need to do it programmatically. I frequently get this question from my students, “How to open a file upload dialog with Javascript?” Today in this article, we are going to answer this.
Code to open file upload dialog with Javascript
<!DOCTYPE HTML> <html> <head> <title>File Upload Using Javascript</title> </head> <body> <form style="display:none"> <input type="file" id="fileDialogId" /> </form> <script> const openFileDialog = () => { document.getElementById('fileDialogId').click(); } setTimeout(openFileDialog, 5000); </script> </body> </html>
There are few things you should know about this code –
- We are using ES6 way of JavaScript formatting.
- Instead of creating file element using JS, we are using the html form. Always remember, in order to write good codes, you should always follow the simplicity. Whenever possible, try to use browser features and html standard tags for maximum compatibility. Here, we are hiding the form to show that it’s not driven by human clicks.
- File dialog will automatically open after 5 seconds.
You may also like –
Let’s understand our code –
First, we are setting a form
with input type="file"
. The id of this field is fileDialogId
. I am hiding this form so that I can show that there is no visual available to open file upload dialog using manual button click.
<form style="display:none"> <input type="file" id="fileDialogId" /> </form>
Next, we are defining a method (openFileDialog()
) using ES6 arrow function. Calling this function will trigger a click event on file upload dialog.
const openFileDialog = () => { document.getElementById('fileDialogId').click(); }
Last, we have used setTimeout
for running openFileDialog
after 5 seconds from page load. This code snippet will open the file upload dialog after 5 seconds.
setTimeout(openFileDialog, 5000);