1. 基本语法
<input type="file" accept="image/*" capture>
-
type="file"
:文件上传。 -
accept="image/*"
:限制只能选择图片。 -
capture
:告诉浏览器 直接调用设备摄像头 / 麦克风 来采集内容,而不是从相册里挑。
2. capture
的可选值
属性值 | 作用 |
---|---|
capture (无值) | 启用默认设备(通常是后置摄像头) |
capture="user" | 启用前置摄像头(自拍) |
capture="environment" | 启用后置摄像头 |
capture="microphone" | 调用麦克风采集音频(需配合 accept="audio/*" ) |
3. 常见用法示例
① 调用后置摄像头拍照
<input type="file" accept="image/*" capture="environment">
② 调用前置摄像头自拍
<input type="file" accept="image/*" capture="user">
③ 调用摄像头拍摄视频
<input type="file" accept="video/*" capture>
④ 调用麦克风录音
<input type="file" accept="audio/*" capture="microphone">
4. 注意事项
-
PC 浏览器大部分不支持,主要针对 移动端浏览器(Safari, Chrome, 微信内置浏览器)。
-
capture
只是 建议,最终是否调用摄像头/麦克风由 浏览器决定。 -
如果没设置
accept
,用户可能依然能选择文件,而不是强制调用摄像头。 -
在 iOS Safari 上,
capture
和accept="image/*"
搭配才能生效。 -
如果要上传后端,需要用 FormData 读取文件并提交。
5. 简单上传 + 预览 Demo
<input type="file" accept="image/*" capture="environment" id="cameraInput">
<br>
<img id="preview" width="200">
<script>
const input = document.getElementById("cameraInput");
const preview = document.getElementById("preview");
input.addEventListener("change", (event) => {
const file = event.target.files[0];
if (file) {
preview.src = URL.createObjectURL(file);
}
});
</script>