Capturing images and videos from the camera of mobile devices using HTML
Collecting and uploading files from the user’s device is a task that most modern web applications need to do every now and then. In such scenarios, the
<input> with the
file type can be used to handle file uploads.
- The demo
- In action
Now, the file input let the user choose one or more existing files from their device storage. But in some situations, you might want to give the user the ability to open the camera of the device, capture the media and upload it to the server.
Turns out, it’s pretty easy to do this by providing just couple more attributes to the
<input> elements with
By providing the additional
accept attributes to the file input, it’s possible to give the user the ability to capture media from the device’s camera/microphone.
Note: These work better on mobile devices. So, if your device is a desktop computer, you’ll likely get a typical file picker.
capture attribute takes in the following two string values that specify which camera to use for the capture of image or video data.
user- The user-facing camera and/or microphone should be used
environment- The outward-facing camera and/or microphone should be used
You can specify what kind of files you want to accept in the
accept attribute. Usually, it can be one of these values.
image/*- To capture any file with an
audio/*- To capture any file with an
video/*- To capture any file with an
Capturing images from the camera
So, if we want the file input to take an image from the device’s camera, here’s how we can do it.
<input type="file" name="photo" capture="user" accept="image/*">
Capturing videos from the camera
To capture a video from the camera, here’s what we can do.
<input type="file" name="video" capture="user" accept="video/*">
Capturing audio from the microphone
And lastly, here’s how to capture an
audio from the device’s microphone.
<input type="file" name="audio" capture="user" accept="audio/*">
I have put together a demo that has all three input combinations. You can try opening this in a browser on the mobile device and see how all these open camera/audio interfaces of the device to capture media.
Watch it in action in this video.