vue 上传图片

159 阅读1分钟
  <div class="xuanz">
            <el-upload
                    class="avatar-uploader"
                    ref="upload"
                    action=""
                    :http-request="upLoad"
                    :show-file-list="false"
                    list-type="picture"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
              <img v-if="headUrl" :src="headUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>

                   beforeAvatarUpload(file) {
                      // const isJPG = file.type === 'image/jpeg';
                      const isLt3M = file.size / 1024 / 1024 < 3;
                      // if (!isJPG) {
                      //     this.$message.error('上传头像图片只能是 JPG 格式!');
                      // }
                      if (!isLt3M) {
                          this.$message.error('上传头像图片大小不能超过 3MB!');
                      }
            
                      // return isJPG && isLt3M;
                      return isLt3M;
                  },
                  
                     handleAvatarSuccess(res, file) {
                          this.headUrl = URL.createObjectURL(file.raw);
                      },
                    upLoad(){
                        this.headUrl = URL.createObjectURL(file.file) // 图片url
                        this.imgurl = file.file // 获取的是 图片的链接
                    }
                    
                  var formData = new FormData(); 上传
                  formData.append('imgurl', this.imgurl); // 图片