antd design vue ` -- upload组件完成图片上传
方式一:利用组件本身的action,需要后端提供服务器,这种一般是阿里云或者七牛云类似的服务器,但是一般企业开发是通过后端给你接口的形式,去上传图片。
方式二:接口上传(formData)
-
接口地址:http://192.168.60.100:9090/manager/baseCustomersPhoto/saveCustPhoto
-
入参:outid(学号用来绑定头像),photo(图片信息)
formData.append('photo', file, fileName)formData.append("outid", *this*.photoOutid) -
组件API
1.
beforeUpload返回false后,手动上传文件。2.
customRequest通过覆盖默认的上传行为,可以自定义自己的上传实现 -
具体实现
1.组件 <a-upload :disabled="isSelectPhoto" name="avatar" list-type="picture-card" class="avatar-uploader" :show-upload-list="false" :customRequest="handlerUpload" :before-upload="beforeUpload"> <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width:100%" /> <div v-else> <a-icon :type="loading ? 'loading' : 'plus'" /> <div class="ant-upload-text"> 上传头像 </div> </div> </a-upload>2.自定义上传的2个钩子函数 beforeUpload(file) { //验证文件格式 const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg'; if (!isJpgOrPng) { this.$message.error('只能上传Jpg图片!'); } //验证文件大小 const isLt2M = file.size / 1024 / 1024 < 1; if (!isLt2M) { this.$message.error('图片大小需在1MB以内!'); } //复制文件信息 this.photoData = file //显示文件 const r = new FileReader(); r.readAsDataURL(file); r.onload = (e) => { this.imageUrl = e.target.result } //不自动上传 return false; }, handlerUpload(file) { //编辑人员信息时,可能存在不修改照片的情况,如果不加判断,会导致没有提示保存成功 //modify by lishiwen //2022-08-18 if (!file) { return; } console.log("上传文件:", file) let fileName = file.name let formData = new FormData() formData.append('photo', file, fileName) formData.append("outid", this.photoOutid) cs.setPhoto(formData, (total, loaded) => { }) },3.在用户保存完表单成功之后调用handlerUpload方法 ds.saveInfo(this.addPeopleInfo).then(result => { if (result.data.code == 200) { // 调用保存图片 this.handlerUpload(this.photoData); this.$message.success('保存用户信息成功') const outid = this.photoOutid; cs.getPhoto({ outid }).then(result => { this.imageUrl = `data:image/png;base64,${result.data.data[0]}` setTimeout(() => { this.visible = false }, 1000) }) this.loading = false; // this.visible = false; this.form.resetFields() this.getGoodList(); this.loading = false } else { console.log('保存用户信息失败'); this.$message.error('保存用户信息失败') this.loading = false; this.visible = false; this.form.resetFields() } })相关代码截图