写毕设遇到个头像上传的问题要求:点击图片选择文件,并显示在头像框里
首先给图片添加点击事件<el-avatar @click.native="upStart" :src="userDetail.upAva.url " :size="50" />
方法如下
upStart() {//创建inputconst upload = document.createElement("input");//设置type为fileupload.type = "file";//类型upload.accept = "image/png, image/jpeg";//添加onchange事件upload.onchange = this.setFile;//模拟点击upload.click();}
onchange方法
setFile(e) {//获取文件const file = e.path[0].files[0];//将其放入formdata中方便上传const formData = new FormData();formData.append("imgFile", file);const ImgUrl = window.URL.createObjectURL(file);//构建Image对象方便获取其宽高const img = new Image();img.src = ImgUrl;img.onload = () => {//只有在图片完成加载的时候才能拿到图片的宽高this.userDetail.upAva.imgSize = img.width;};this.userDetail.upAva.url = ImgUrl;}
图片文件和图片宽高都有了,就可以将这个formdata就行上传了。