標籤:images 提交 小數 top base64編碼 監聽 height color change
實現圖片上傳的方法有很多,這裡我們介紹比較簡單的一種,使用base64對圖片資訊進行編碼,然後直接將圖片的base64資訊存到資料庫。
但是對於系統中需要上傳的圖片較多時並不建議採用這種方式,我們一般會選擇存圖片路徑的方式,這樣有助於減小資料庫壓力,base64
編碼後的圖片資訊是一個很長的字串,一般我們使用longText類型來將其存入資料庫。
html代碼如下:
<div class="col-sm-6"> <img id="headPortraitImgShow" src="img/defaultHeadPoint.jpg" alt="" width="160px" height="180px" /> <input type="file" id="headPortraitUpload" style="margin-top:10px;"></div>
javaScript代碼如下:
$("#headPortraitUpload").on("change",headPortraitListener);
/*定義全域變數存貯圖片資訊*/
var base64head="";
/*頭像上傳監聽*/function headPortraitListener(e) { var img = document.getElementById(‘headPortraitImgShow‘); if(window.FileReader) { var file = e.target.files[0]; var reader = new FileReader(); if (file && file.type.match(‘image.*‘)) { reader.readAsDataURL(file); } else { img.css(‘display‘, ‘none‘); img.attr(‘src‘, ‘‘); } reader.onloadend = function (e) { img.setAttribute(‘src‘, reader.result); base64head = reader.result; } }}
效果預覽:預設圖片-----》
最後,將base64head提交到後台存入資料庫即可,下次從資料庫取出直接將該base64資訊放到img標籤的src裡面圖片就回顯出來了
js實現圖片上傳預覽功能,使用base64編碼來實現