在laravel中使用vue js上传多个文件,我的验证就像
$request->validate([
'title' => 'required',
'pics.*' => 'required|image|mimes:jpeg,png,jpg,gif'
]);
我的组件如下所示
<template>
<div class="col-md-6">
<div class="form-group">
<label>Title</label>
<input id="title" type="text" ref="myDiv" v-model="title" class="form-control" name="title">
<div v-cloak><label class="error" v-if="errors['title']">{{ errors.title[0]
}}</label></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Upload Files</label>
<input id="uploadfile" type="file" ref="pics" name="pics[]" multiple class="form-control" @change="fieldChange">
<div v-cloak><label class="error" v-if="errors['pics']">{{ errors.pics[0] }}</label></div>
</div>
</div>
</template>
export default {
data(){
return {
attachments:[],
pics : [],
errors: [],
form: new FormData
}
},
methods:{
fieldChange(e){
let selectedFiles=e.target.files;
if(!selectedFiles.length){
return false;
}
for(let i=0;i<selectedFiles.length;i++){
this.attachments.push(selectedFiles[i]);
}
console.log(this.attachments);
},
uploadFile() {
this.errors = [];
this.form.append('img',this.attachments2);
if(this.attachments.length > 0){
for(let i=0; i<this.attachments.length;i++){
this.form.append('pics[]',this.attachments[i]);
}
}else {
this.form.append("pics", '');
}
//this.form.append('')
const config = { headers: { 'Content-Type':
'multipart/form-data' } };
axios.post('/admin/theme/',this.form,config).then(response=>
{
this.pics = [];
}).catch((error) => {
this.errors = error.response.data.errors;
console.log(this.errors.pics);
});
}
},
mounted() {
console.log('Component mounted.')
}
}
如果我单击“提交”按钮,则标题为空,但错误打印,但没有多个文件错误,则显示错误,但不打印
pics.0:[“必填pics.0字段。”]
但是标题字段验证错误可以完美打印
请任何人帮助我使用vue js打印多个文件上传错误
答案 0 :(得分:0)
要显示所有错误,您需要循环从Laravel返回的errors数组:
// display title errors
<div v-if="Array.isArray(errors.title) && errors.title.length"
v-for="(error, index) in errors.title"
:key="index">
{{ error }}
</div>
// display pics errors
<div v-if="Array.isArray(errors.pics) && errors.pics.length"
v-for="(error, index) in errors.pics"
:key="index">
{{ error }}
</div>