js 调用手机摄像头或相册并展示图片

 

效果图

手机浏览器、微信打开该网页,都支持调用摄像头拍照和打开相册。

先看最终结果: 

 每次点击“点击上传”,可以选择相册或者拍照,选完以后可以多展示一张图片,同时上传服务器。

点击“重新上传”,清空所有图片。

 

 

PC浏览器打开,类似,不过只能选择图片文件:

 

 

 代码

 

把input type=file的标签透明度设置为0,使用绝对布局的方式用另一个标签覆盖它:

<div id="imgPreview">
    <div id="prompt3">
        <div id="imgSpan">
            点击上传
        </div>
        <input type="file" id="file" class="filepath" onchange="changepic()" accept="image/*">
        <button id="imgSpan" type="button" onclick="clearpic()">重新上传</button>
    </div>
    @*此处用js自动插入图片标签<img src="" id="img3" />*@
</div>

 

获取到图片以后在前端展示图片:

function changepic() {
    var reads = new FileReader();
    f = document.getElementById('file').files[0];
   savePic(f); --》》 保存图片,上传服务器 reads.readAsDataURL(f); reads.onload
= function (e) { var y = document.createElement('img'); y.id = "img3"; y.src = this.result; $("#imgPreview").append(y); }; };
上传服务器:
function savePic(file) {
    var formData = new FormData();
    formData.append('file', file);

    $.ajax({
                url: "https://www.aaaa.com/fileupload",
                type: "post",
                data: formData,
                contentType: false,
                processData: false,
                success: function (data) {
                    var picId = JSON.parse(data).atts[0].id;   -->> 解析服务器返回的json字符串,取出其中的Id
                    alert("返回值id为:"+picId);
                },
                error: function (data) {
                    alert("上传失败");
                }
      });
}                                                               

通过遍历删除第一个以外的所有标签(第一个标签是上传和清空的按钮):

function clearpic() {
    var x = document.getElementById('imgPreview');
    var count = x.childElementCount;
    alert(count);
    for (var i = 1; i < count;i++) {   
        x.removeChild(x.children[1]);
    }
};

 

css 样式:

#imgPreview {
    width: 100%;
    height: 120px;
    margin: 10px auto 0px auto;
    border: 0.5px solid #ced4da;
    text-align: left;
    vertical-align: central;
}

#prompt3 {
    height: 30px;
    width: 200px;
    position: relative;
}

#imgSpan {              -》》 两个按钮的样式
    position: relative;
    height: 30px;
    background: #fff; /*#ccc;*/
    border: 1px solid #333;
    left: 0;
    top: 1px;
    padding: 5px 10px;
    overflow: hidden;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
    border-radius: 20px;
    color: #333;
    font-size: 13px;
    display: inline;
}

.filepath {
    position: absolute;    -》》绝对布局
    left: 0;
    top: 0;
    height: 30px;
    width: 80px;
    opacity: 0;          -》》 透明度设置为0,即隐藏
}

#img3 {
    position: relative;
    height: 90px;
    width: 90px;
    padding: 2px;
    display: inline;       -》》inline是为了让所有图片不换行
}

posted on 2019-08-17 19:22  张宏伟同学  阅读(8496)  评论(0编辑  收藏  举报

导航