How to open the select file dialog via JavaScript?

To open the file select dialog via JavaScript, we can trigger a click event on an <input type="file"> element.

To do this, we:

HTML:

<input type="file" id="fileInput" style="display: none;">
<button onclick="openFileDialog()">Open File Dialog</button>

JavaScript:

function openFileDialog() {
    // Trigger a click event on the file input element
    var fileInput = document.getElementById('fileInput');
    fileInput.click();

    // Add an event listener to handle file selection
    fileInput.addEventListener('change', handleFileSelect);
}

function handleFileSelect(event) {
    // Handle the selected file(s) here
    var selectedFiles = event.target.files;
    console.log(selectedFiles);
}

In this example, clicking the button triggers the openFileDialog function, which programmatically clicks the <input type="file"> element.

This action opens the file select dialog. When a file is selected, the handleFileSelect function is called, where we can handle the selected file(s) as needed.