1.html代码(action是后端地址,如果要带别的参数:data={id:this.keyid})
<el-upload
class="avatar-uploader"
:data={id:this.keyid}
:action=imageUrl
name="file"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img
v-if="imglogin"
:src="imglogin"
class="avatar"
>
<i
v-else
class="el-icon-plus avatar-uploader-icon"
></i>
</el-upload>
2.事件(:on-success是上传成功执行的函数,用action忘后端传,前端成功,响应没有东西,但是后端收不到,不知道什么原因,所以我直接在on-success中调取后端接口,传file格式用formData方法传)
handleAvatarSuccess(res, file) {
console.log(res)
this.imglogin = URL.createObjectURL(file.raw);
console.log(this.imageUrl)
},
beforeAvatarUpload(file) {
const isJPG = file.type === "image/jpeg";
const isLt2M = file.size / 1024 / 1024 < 10;
if (!isJPG) {
this.$message.error("上传头像图片只能是 JPG 格式!");
}
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!");
}
let formData = new FormData();
formData.append("file", file);
formData.append("id", this.keyid);
getsendupoade(formData).then(res=>{
if(res.code==20000){
this.dialogVisibleoplod=false
}
})
return isJPG && isLt2M;
},