前段時間基于微信公眾號做了一個投票的活動。項目中涉及到用戶報名需要添加圖片,整理下上傳圖片的代碼,希望對大家有幫助
<--tpl文件-->
//input選擇文件,直接隱藏,js里添加onClick方法
<input class="imageinput" style="display: none;" type="file" accept="image/jpeg,image/jpg,image/png">
//為選擇圖片前的樣式,
<div class="input_ImageItem">
//選擇圖片的按鈕
//這是一個img標簽,顯示錯誤 id="chooseImage" class="chooseImage"
<span class="upLoadText">上傳合照.png</span>
</div>
//選擇圖片之后的樣式
<div class="showImage" style="display: none;">
//用于展示圖片的img
<img class="imageView"/>
//更換圖片的按鈕
//這是一個img標簽,顯示錯誤class="alertImage"
</div>
<div class="input_box" id="user_box" data-opid="{%$openid%}">
//這是一個img標簽,顯示錯誤class="btn_submit"
</div>
<--js文件-->
//用于保存選擇的圖片的base64編碼的數據
var imagUrl;
var init = function(){
bindActive();
}
function bindActive(){
//點擊時調用input選擇圖片
$(".input_ImageItem").on('click', function() {
console.log('選擇圖片')
//調用input
$(".imageinput").click();
})
//點擊時調用input選擇圖片
$(".alertImage").on('click', function() {
console.log('選擇圖片')
$(".imageinput").click();
})
//input選擇文件后調用的方法
$(".imageinput").change(function() {
didLoadImage(this);
});
$(".input_box").on('click',function(){
submit();
})
}
function didLoadImage(x){
//取出選擇的圖片
var fileInput = x.files[0];
//判斷是否選擇了圖片
if(x.files && x.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
//此處得到是圖片的base64編碼數據
imagUrl = e.target.result;
console.log(e);
$(".imageView").attr('src', imagUrl);
//展示哪個樣式
if(imagUrl) {
$('.showImage').css('display', 'inline-flex');
$(".input_ImageItem").css('display', 'none');
} else {
$(".upLoadText").css('display', 'inline-flex');
$(".imageView").css('display', 'none');
}
};
reader.readAsDataURL(x.files[0]);
}
}
//手動提交方式:點擊提交按鈕后直接把imagUrl當做參數傳給后臺,后臺把imagUrl解析就是該圖片(imagUrl是圖片的base64編碼后的數據)
function submit(){
}
效果圖如下
圖片.png
圖片.png
有什么問題可以在下面評論,大家一起探討
后面會整理多張圖片的選擇、預覽、上傳