Refenerce:
https://github.com/Tencent/weui.js/blob/master/example/example.js
还得记得引入jquery,weui.css,weui.js呀
html:
<div class="weui-cells weui-cells_form" id="uploader">
<div class="weui-cell">
<div class="weui-cell__bd">
<div class="weui-uploader">
<div class="weui-uploader__hd">
<p class="weui-uploader__title">图片上传</p>
<div class="weui-uploader__info"><span id="uploadCount">0</span>/5</div>
</div>
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="uploaderFiles"></ul>
<div class="weui-uploader__input-box">
<input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" capture="camera" multiple="" />
</div>
</div>
</div>
</div>
</div>
</div>
js:
var uploadCount = 0, uploadList = [];
var uploadCountDom = document.getElementById("uploadCount");
weui.uploader('#uploader', {
url: '../../houseReleaseController/upLoadPictrues',
auto: true,
type: 'file',
fileVal: 'fileList',
onBeforeQueued: function(files) {
// `this` 是轮询到的文件, `files` 是所有文件
if(["image/jpg", "image/jpeg", "image/png", "image/gif"].indexOf(this.type) < 0){
weui.alert('请上传图片');
return false; // 阻止文件添加
}
if(this.size > 10 * 1024 * 1024){
weui.alert('请上传不超过10M的图片');
return false;
}
if (files.length > 5) { // 防止一下子选择过多文件
weui.alert('最多只能上传5张图片,请重新选择');
return false;
}
if (uploadCount + 1 > 5) {
weui.alert('最多只能上传5张图片');
return false;
}
++uploadCount;
uploadCountDom.innerHTML = uploadCount;
},
onQueued: function(){
/* console.log(this); */
uploadList.push(this);
imgsArr.push(this.url);
},
onSuccess: function (ret) {
/* console.log(this, ret); */
localStorage.setItem("imgsrc", JSON.stringify(imgsArr));
console.log(imgsArr);
console.log(localStorage.getItem("imgsrc"));
submitFlag = true;
},
onError: function(err){
/* console.log(this, err); */
}
});
//缩略图预览
document.querySelector('#uploaderFiles').addEventListener('click', function(e){
var target = e.target;
while(!target.classList.contains('weui-uploader__file') && target){
target = target.parentNode;
}
if(!target) return;
var url = target.getAttribute('style') || '';
var id = target.getAttribute('data-id');
if(url){
url = url.match(/url((.*?))/)[1].replace(/"/g, '');
}
var gallery = weui.gallery(url, {
className: 'my-custom-name',
onDelete: function(){
weui.confirm('确定删除该图片?', function(){
--uploadCount;
uploadCountDom.innerHTML = uploadCount;
var newImgs = JSON.parse(localStorage.getItem('imgsrc'));
var imgIndex =0;
$('.weui-uploader__file').each(function(index){
$(this).click(function(){
console.log($(this).index());
imgIndex = $(this).index();
})
})
imgsArr.splice(imgIndex,1);
newImgs.splice(imgIndex,1);
console.log(newImgs);
localStorage.setItem('imgsrc',JSON.stringify(newImgs));
for (var i = 0, len = uploadList.length; i < len; ++i) {
var file = uploadList[i];
if(file.id == id){
file.stop();
break;
}
}
target.remove();
gallery.hide();
});
}
});
});