一:頁面定義app
<div class="item-content item-input"> <div class="item-inner"> <div class="item-title item-label">照片登記</div> <div class="item-input-wrap"> <input id="upload_image" type="file" name="upload_image" accept="image/*" capture="camera" required validate data-error-message="請上傳登記圖片!" onchange="upload('#upload_image', '#customer_image');"/> </div> </div> </div> <div class="item-content item-input"> <div class="item-inner"> <div class="item-title item-label">照片預覽</div> <div class="item-input-wrap"> <img class="lazy lazy-fade-in" id="customer_image" src="/jd_ct_terminal/static/app/img/preview.png" style="width:80%;text-align:center;"> </div> </div> </div>
二:JS代碼ui
//照片 var photo = null //上傳圖片 function upload(upload_id, preview_id) { var $upload = document.querySelector(upload_id), $preview = document.querySelector(preview_id), file = $upload.files[0], reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { //獲取照片,並設置給預覽div呈現 photo = e.target.result //獲取圖片內容:base64字符串 $preview.setAttribute("src", photo); }; };
三:後臺提取圖片spa
此處的base64字符串是帶前綴的,須要截除。code
photo = photo.split(',')[1]