首页 > 解决方案 > Image is not validating: "The avatar must be an image"

问题描述

I'm using a modal to preview an avatar. The even that triggers the modal is outside the ability to have a parent child structure so I have to pass the file object to my UpdateAvatar component.

Html

<avatar-update :image-blob="avatarFile" :show="avatarModalShow" 
               @close="avatarModalShow = !avatarModalShow" 
               :change-avatar="updateCrop"> </avatar-update>

Root Instance

data() {
    return {
        avatarModalShow: false,
        avatarFile: null,
    }
},

methods: {
    onFileChange: function(e) {
        this.avatarFile = e.target.files[0];
        this.avatarModalShow = !this.avatarModalShow;
  },
},

AvatarUpdate

export default {
    props: ['show','imgUrl','changeAvatar','imageBlob'],
    data() {
      return {
        image: null,
        message: null,
        internalImageObj: null
      }
    },
    watch: {
      changeAvatar: function(){     
          this.image = this.imgUrl;
      },
      imageBlob: function (newVal) {
        let reader  = new FileReader()
        reader.readAsDataURL(newVal)
        reader.addEventListener('load', () => {
          this.internalImageObj = reader.result
        }, false)  
      }
    },
    updated: function () {
      this.image = this.imgUrl;      
    },
    methods: {
        close: function(){
          this.$emit('close');
        },

        submitAvatar: function(){


          const avatarFormData = new FormData();
          avatarFormData.append('avatar', this.internalImageObj);
          console.log(avatarFormData);

          axios({
              method: 'POST',
              url: '/profile/avatar',
              data: avatarFormData,
          }).then(function (response) {


          this.message = "Your avatar has been submitted";   

          }.bind(this))
          .catch(function (error) {
              console.log(error);
          });
        }
    }
}

UserController

public function avatar(Request $request)
{
    $request->validate([
        'avatar' => 'image',
    ]);

    return $request->all();
}

When I return $request->all(); in the avatar function with no validation on the UserController I'm getting this output: avatar:"data:image/png;base64,iVBORw0KGgoAAAANSUhSomeLongString

Error

{message: "The given data was invalid.", errors: {avatar: ["The avatar must be an image."]}} errors : {avatar: ["The avatar must be an image."]} avatar : ["The avatar must be an image."] 0 : "The avatar must be an image." message : "The given data was invalid."

标签: laravelvue.js

解决方案


这是因为您的验证规则avatarisimagemimes:jpeg,bmp,pngthis 它将查找 mime 类型为 jpeg、bmp、png 的文件。但在您的情况下,您axios将其作为没有 mime 类型的 base64 发送。你需要'Content-Type': 'multipart/form-data'像这样在你的 axios 对象中包含标题,

axios({
   method: 'POST',
   url: '/profile/avatar',
   data: avatarFormData,
   headers: {
    'Content-Type': 'multipart/form-data'
   }
 })

希望这可以帮助。


推荐阅读