HTML5 input type="file" accept="image/*" capture="camera" display as image rather than choose file button

Use the JavaScript FileReader to allow users to choose an image file and display it as an image instead of showing the default file input button. This approach provides a better user experience by giving immediate visual feedback when an image is selected.

The HTML5 input element with type="file", accept="image/*", and capture="camera" attributes allows users to select images from their device or capture photos directly from the camera on mobile devices.

HTML Structure

First, let's create the basic HTML structure with a file input and an image element ?

<form id="myform">
    <input type="file" id="myimg" accept="image/*" capture="camera" onchange="readURL(this)" />
    <img id="myid" src="#" alt="Selected image" style="max-width: 300px; display: none;" />
</form>

JavaScript Implementation

Here is the JavaScript function using FileReader to read and display the selected image ?

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        
        reader.onload = function (e) {
            document.getElementById('myid').src = e.target.result;
            document.getElementById('myid').style.display = 'block';
        }
        
        reader.readAsDataURL(input.files[0]);
    }
}

Complete Working Example

Here's the complete code combining HTML and JavaScript ?

<!DOCTYPE html>
<html>
<head>
    <title>Image File Input Display</title>
</head>
<body>
    <form id="myform">
        <input type="file" id="myimg" accept="image/*" capture="camera" onchange="readURL(this)" />
        <br><br>
        <img id="myid" src="#" alt="Selected image" style="max-width: 300px; display: none; border: 1px solid #ccc;" />
    </form>

    <script>
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            
            reader.onload = function (e) {
                document.getElementById('myid').src = e.target.result;
                document.getElementById('myid').style.display = 'block';
            }
            
            reader.readAsDataURL(input.files[0]);
        }
    }
    </script>
</body>
</html>

How It Works

The FileReader.readAsDataURL() method reads the selected file and converts it to a base64-encoded data URL. When the file is loaded, the onload event fires, and the image source is set to display the selected file immediately.

The accept="image/*" attribute filters the file picker to show only image files, while capture="camera" enables direct camera access on mobile devices.

Conclusion

Using FileReader with HTML5 file input provides an elegant solution to display selected images instantly, creating a more interactive and user-friendly file upload experience.

Updated on: 2026-03-13T09:45:39+05:30

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements