element-ui中上传图片组件的使用

<el-upload
   class="avatar-uploader"
    action=""  
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

 beforeAvatarUpload(file) { //上传前的函数
//上传前对图片类型和大小进行判断
   const isJPG = file.type === 'image/jpeg';
   const isLt2M = file.size / 1024 / 1024 < 2;

   if (!isJPG) {
     this.$message.error('上传头像图片只能是 JPG 格式!');
   }
   if (!isLt2M) {
     this.$message.error('上传头像图片大小不能超过 2MB!');
   }
   //校验成功上传文件
   if(isJPG && isLt2M == true){
     console.log(file);

     //将文件转化为formdata数据上传
     let fd = new FormData()
     fd.append('files', file)
     console.log(fd)
  
   // post上传图片

      let that = this
    
       new Promise(function (resolve, reject) {
           axios.post('图片上传的路径', fd, 
                 {
                 headers: {
                 'Content-Type': 'multipart/form-data'
                 }
               }).then((response) => {
                  that.imgId = response.data.data
                   resolve(that.imgId);
               }).catch((error) =>{
                   this.$message.error('头像上传失败,请重新上传!');
               })
              }).then(function (id){
                  console.log(id)
           //    that.axios.get('/file/view/'+id)
           //     .then((response) => {
           //          that.imageUrl = response.request.responseURL;
           //      })
         })         
       }
             return isJPG && isLt2M;

 },
发布了47 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/wuwenjie_1997/article/details/105095107