laravel - 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."
解决方案
这是因为您的验证规则avatar
isimage
或mimes:jpeg,bmp,png
this 它将查找 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'
}
})
希望这可以帮助。
推荐阅读
- google-bigquery - 从 BigQuery UDF 中的参数查询表
- android - 如何查看已在 Cloud Firestore 中读取的所有数据?
- .net - 如何从 WebView2 中的 ExecuteScriptAsync 获取同步返回
- javascript - 共享时组件找不到导入的元素
- python - 谷歌日历凭据处理
- c# - 如何保持不同的线程有自己的变量计算?
- vba - 使用 VBA 在 MS Word 中进行条件格式设置
- c# - Can Radio Buttons be used in Xamarin.Forms?
- ios - 使用 Combine 发布 API 请求时遇到问题
- python - How to write to a directory os agnostic?