首页 > 解决方案 > Laravel 验证文件扩展名?

问题描述

我有以下 FormRequest 验证Files,特别是音频文件:

public function rules()
{
    return [
        'file' => 'bail|required|file|mimes:mpeg,mp3,mp2,aiff,wav,wave,flac,m4a,caf,ogg,aac,amr,wma|max:500000000'
    ];
}

但是,由于某种原因,当我上传任何类型的音频文件时,我会收到一条422说明文件类型无效的消息……这是什么原因?

更新

这是我的ajax使用axios

const f = new FormData()
f.append('file', file)
const config = {
headers: {
'Content-Type':'multipart/form-data'
}
}
return axios.post('myendpoint', f, config).then((response) => {
// handle
}).catch((thrown) => {
if (axios.isCancel(thrown)) {
return console.log('Request canceled', thrown.message);
}
return console.log(thrown)
})

标签: laravelfilevalidationmime-types

解决方案


你的表格中有这个:

enctype=“multipart/form-data"

编辑:为了正确地将您上传的文件附加到 FormData,您需要在以下位置使用onchange事件:

输入

<input type=“file” onchange=“getFile”&gt;

处理程序

function getFile(event) {
   file = event.target.files
}

阅读此处了解更多信息。


推荐阅读