在项目中用到了原生的上传功能,html5代码如下
<div class="uploadimg"><div v-for="(item, index) in checkList" :key="index" ><imageclass="mask":src="checkList[index]"place-holder="imageLoad('person-center-doctor-default.png')"@click="picClick(item)"></image><image class="img-cancel" v-if="item" :src="imageLoad('erase',true)" @click="imgCancel(index,'check')"></image></div><imageclass="mask"@click="addClick('check')":src="imageLoad('add', true)"></image></div>
列表循环显示的是已经上传的图片,点击功能为添加的预览功能,下面的image标签为相对定位的删除图标,点击可删除对应图片,最下面的image是点击上传图标,点击图标可上传对应图片。
再来看下js代码
imgCancel(index,type){this.checkList.splice(index,1)},addClick(type) {if(type=='check'&&this.checkList.length>8){normal.toast("最多上传9张图片");return}if(type=='desc'&&this.miaoShuList.length>8){normal.toast("最多上传9张图片");return}this.chooseFile().then((res) => {let file = res;console.log(res);let fileUrl = URL.createObjectURL(file[0]); // 获取文件urlconsole.log("输出选择的图片的路径 :", fileUrl, file, this.idCardUrl);if (fileUrl.length == 0) {return;}// let imgList = [];// imgList.push({// src: file[0].name,// });let param = new FormData(); // 创建form对象param.append("file", file[0], file[0].name); // 通过append向form对象添加数据// alertUtil.loading(true, "正在上传中...");var cacheUrl = api.UPLOAD_PATIENT_IMAGE + "?token=" + userInfoCache.getUserToken();business.req("post",cacheUrl,param,function (resp) {// this.portrait = resp.extra;if(type=='desc'){this.miaoShuList.push(resp.extra);}else if(type=='check'){this.checkList.push(resp.extra)}// normal.saveStorage(// cacheKeys.PhotoImageUrl,// this.portrait,// function () {}// );normal.toast("图片上传成功");console.log("this.portrait========", resp.extra);}.bind(this),function(err){console.log(err);normal.toast("超时");}.bind(this));});},//唤起上传文件chooseFile() {return new Promise((resolve, reject) => {let fileinput = document.createElement("input");fileinput.type = "file";// fileinput.multiple = truefileinput.accept = "image/*";fileinput.setAttribute("style","position:fixed;left:-500px;top:-500px;");fileinput.addEventListener("change", () => {resolve(fileinput.files);document.body.removeChild(fileinput);if (!fileinput.files || fileinput.files.length === 0)reject(new Error("文件选择出错"));});document.body.appendChild(fileinput);fileinput.click();});},//点击进行图片预览picClick(item){console.log(item);let pswpElement = document.querySelectorAll('.pswp')[0];let items=[{src:item,w:200,h:200}]let options = {pinchToClose:true,shareEl:false,tapToToggleControls:false,tapToClose:true,index:0 };let gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);gallery.init();},
预览功能用的photoswipe插件,采用的cdn引入的方式,在index.html中引入地址如下
<link rel="stylesheet" href="/ajax/libs/photoswipe/4.1.1/photoswipe.min.css"><link rel="stylesheet" href="/ajax/libs/photoswipe/4.1.1/default-skin/default-skin.min.css"><script src="/ajax/libs/photoswipe/4.1.1/photoswipe.min.js"></script><script src="/ajax/libs/photoswipe/4.1.1/photoswipe-ui-default.min.js"></script>
然后在app.vue页面还要加上如下代码
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true"><!-- Background of PhotoSwipe. It's a separate element as animating opacity is faster than rgba(). --><div class="pswp__bg"></div><!-- Slides wrapper with overflow:hidden. --><div class="pswp__scroll-wrap"><!-- Container that holds slides. PhotoSwipe keeps only 3 of them in the DOM to save memory.Don't modify these 3 pswp__item elements, data is added later on. --><div class="pswp__container"><div class="pswp__item"></div><div class="pswp__item"></div><div class="pswp__item"></div></div><!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. --><div class="pswp__ui pswp__ui--hidden"><div class="pswp__top-bar"><!-- Controls are self-explanatory. Order can be changed. --><div class="pswp__counter"></div><buttonclass="pswp__button pswp__button--close"title="Close (Esc)"></button><buttonclass="pswp__button pswp__button--share"title="Share"></button><buttonclass="pswp__button pswp__button--fs"title="Toggle fullscreen"></button><buttonclass="pswp__button pswp__button--zoom"title="Zoom in/out"></button><!-- Preloader demo https://codepen.io/dimsemenov/pen/yyBWoR --><!-- element will get class pswp__preloader--active when preloader is running --><div class="pswp__preloader"><div class="pswp__preloader__icn"><div class="pswp__preloader__cut"><div class="pswp__preloader__donut"></div></div></div></div></div><divclass="pswp__share-modal pswp__share-modal--hidden pswp__single-tap"><div class="pswp__share-tooltip"></div></div><!-- <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button><button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button> --><div class="pswp__caption"><div class="pswp__caption__center"></div></div></div></div></div>
样式如下
.pswp__top-bar {display: inline !important;}
完成上述代码后,预览图片时直接调用预览方法即可不需要额外引入
如果觉得《原生js实现图片上传功能》对你有帮助,请点赞、收藏,并留下你的观点哦!