效果圖
手機瀏覽器、微信打開該網頁,都支持調用攝像頭拍照和打開相冊。
先看最終結果:
每次點擊“點擊上傳”,可以選擇相冊或者拍照,選完以后可以多展示一張圖片,同時上傳服務器。
點擊“重新上傳”,清空所有圖片。
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是為了讓所有圖片不換行 }