html5 <输入类型=“文件”接受=“图像/*” 捕获=“相机”>显示为图像而不是“选择文件”按钮

2022-08-30 10:52:00

我一直在研究使用html 5从我的web应用程序拍摄照片,并使用php将图像上传到数据库 - 现在这工作正常。<input type="file" accept="image/*" capture="camera">

但是,我似乎可以找到显示“拍照”选项的唯一方法是通过一个文本字段,其中包含一个名为“选择文件”的按钮

有没有办法能够单击现有图像以打开拍摄照片选项,然后在用户拍摄/选择照片文件后显示新图像而不是现有照片?然后,如果他们愿意保存图像,则应单击“上传”按钮。

在这里看到JS小提琴,希望这有意义!http://jsfiddle.net/6dxGY/


答案 1

为此,您必须使用Javascript Filereader。(文件阅读器 api 简介:http://www.html5rocks.com/en/tutorials/file/dndfiles/)

用户选择图像后,您可以读取所选图像的文件路径并将其放入html中。

例:

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

Javascript:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

答案 2

我知道这是一个老问题,但我在尝试解决同样的问题时遇到了它。我认为值得分享这个我在其他任何地方都找不到的解决方案。

基本上,解决方案是使用CSS来隐藏元素,并在其周围设置一个看起来像按钮的样式。单击“运行代码段”按钮以查看结果。<input><label>

我之前使用过JavaScript解决方案,效果也很好,但是仅使用CSS即可解决“演示”问题。

label.cameraButton {
  display: inline-block;
  margin: 1em 0;

  /* Styles to make it look like a button */
  padding: 0.5em;
  border: 2px solid #666;
  border-color: #EEE #CCC #CCC #EEE;
  background-color: #DDD;
}

/* Look like a clicked/depressed button */
label.cameraButton:active {
  border-color: #CCC #EEE #EEE #CCC;
}

/* This is the part that actually hides the 'Choose file' text box for camera inputs */
label.cameraButton input[accept*="camera"] {
  display: none;
}
<!DOCTYPE html>
<html>

<head>
  <title>Nice image capture button</title>
</head>

<body>
  <label class="cameraButton">Take a picture
    <input type="file" accept="image/*;capture=camera">
  </label>
</body>

</html>

推荐