Laravel5.8+Vue2项目Axios传图仍报file must be an image错误
问题描述
基于laravel 5.8和vue 2开发应用时,通过axios传输图片,即使提交的是合法图片文件,仍返回file must be an image验证错误。
相关代码
上传组件模板
<div class="row"> <div class="col-md-12 form-group"> <input type="file" name="file" id="file" multiple class="form-control" @change="setFile"> </div> </div>
Vue data对象定义
data(){ return { form: new FormData, amount: null, selectedBmonths: [], student: null, bmonths: [], result: null, errors: null, } },
文件选择setFile方法
setFile(event) { for(const file of event.target.files) this.form.append('files[]', file); }
表单提交submitForm方法
submitForm() { this.clearErrors(); this.form.append('student_id', this.student.stdId); this.form.append('batchId', this.student.batchId); this.form.append('batchfee', this.student.fee); this.form.append('amount', this.amount); for (var i = 0; i < this.selectedBmonths.length; i++) { this.form.append('selectedBmonths[]', this.selectedBmonths[i]); } const config = { headers: {'Content-Type': 'multipart/form-data' }}; axios.post('/university/api/discounts', this.form, config) .then(response => { //this.$router.push('/university/discounts/' + response.data.id); console.log(response.data); }) .catch(errors => { this.errors = errors.response.data.errors; console.log(this.errors); for(const key in this.form) { if(this.errors && this.errors[key] && this.errors[key].length > 0) { document.getElementById('err' + key).innerHTML = this.errors[key][0]; } } }); },
Laravel后端验证逻辑
private function validateData() { return request()->validate( [ 'batchId' => 'required|integer', 'batchfee' => 'required|integer', 'amount' => 'required|integer|lte:batchfee', 'student_id' => 'required|integer', 'selectedBmonths' => 'nullable|array', 'files.*' => 'image', ], [ 'amount.lte' => 'Discount should be less than or equal to the batch fee.', ] ); }
报错截图

说明:已经正确配置了multipart/form-data请求头,但仍然出现图片验证错误。
问题原因
手动指定Content-Type: multipart/form-data请求头时,没有携带boundary分隔符参数,后端无法正确解析上传的文件内容,会把文件字段识别为普通字符串,导致image验证规则判定失败。
浏览器原生发送FormData类型请求体时,会自动生成携带正确boundary值的Content-Type头,手动写死该头会覆盖浏览器的自动配置,导致解析异常。
修复方法
- 删除axios请求配置中手动设置的
Content-Type头,直接提交FormData对象即可,浏览器会自动补全正确的请求头,修改提交部分代码如下:
// 移除原有手动配置headers的config定义 axios.post('/university/api/discounts', this.form) .then(response => { console.log(response.data); }) .catch(errors => { // 原有错误处理逻辑保持不变 this.errors = errors.response.data.errors; console.log(this.errors); for(const key in this.form) { if(this.errors && this.errors[key] && this.errors[key].length > 0) { document.getElementById('err' + key).innerHTML = this.errors[key][0]; } } });
- 额外排查项:
- 确认PHP配置中
file_uploads = On - 确认上传文件大小未超过
php.ini中upload_max_filesize、post_max_size的配置限制,配置值过小会导致文件接收失败触发验证错误 - 确认上传的图片文件后缀属于Laravel默认支持的图片类型(jpg、jpeg、png、gif、bmp、svg、webp),如果是特殊格式图片需要在image规则后补充mimes规则指定允许的后缀
- 确认PHP配置中
内容的提问来源于stack exchange,提问作者Abdul Raheem Ghani
相关产品推荐
相关产品推荐

