Laravel:如何基于mime类型验证同一文件上的多个大小规则
你好,伟大的苏黎世人民 我希望你们都有一个美好的一天 我想根据他们的mime类型验证上传的文件 如果文件是图像,最大大小为2Mb 如果文件是视频,最大大小为500Mb Atm,这是我的代码片段Laravel:如何基于mime类型验证同一文件上的多个大小规则,laravel,validation,Laravel,Validation,你好,伟大的苏黎世人民 我希望你们都有一个美好的一天 我想根据他们的mime类型验证上传的文件 如果文件是图像,最大大小为2Mb 如果文件是视频,最大大小为500Mb Atm,这是我的代码片段 public function upload(Request $request) { $request->validate([ 'file.*' => ['required', 'file', 'mimes:jpg,jpeg,png,mp4', 'max:2048']
public function upload(Request $request) {
$request->validate([
'file.*' => ['required', 'file', 'mimes:jpg,jpeg,png,mp4', 'max:2048'] // 2 Mb for images / photos, *but how to put maximum size for video?*
]);
...
}
如您所见,我将:max:2048
,这是图像的最大大小
我想允许用户上传高达500Mb的视频
更新
我可以根据它们在JavaScript上的模拟来区分每种文件类型
// Example: (Some snippet from my code)
var files = Array.prototype.slice.call(event.target.files)
$formData = new FormData
files.forEach((f, i) => {
var fType = f.type.lowerCase()
// or if you want to get file ext,
// use this: f.name.substr(f.name.lastIndexOf('.') + 1, f.name[length - 1])
// 'example_image.jpeg' > 'jpeg'
// 'example_video.mp4' > 'mp4'
// Here, we can validate the files
// Example:
// You can use regex here, but I prefer to use an array of string, so for future update, if I ever want to 'whitelist' new ext, I can easily add them to this array
if (['image/jpeg', 'image/jpg', 'image/png'].indexOf(fType) !== -1) {
// File is an image with format: jpe?g / png
if ((f.size / 1024) < 2048) {
// Image size is less than 2Mb, valid
$formData.append(['image[' + i + ']', f); // f is the file, see forEach above
}
}
if (['video/mp4'].indexOf(fType) !== -1) {
// File is a video
if ((f.size / 1024) < 512000) {
// Video size is less than 500 Mb, valid
$formData.append(['video[' + i + ']'), f);
}
}
// else: error (file is not an image / video)
... // XHR upload call
})
如果您想知道错误是哪个索引:
// *NOTE* I'm using Vue & Axios here
Object.entries(exc.response.data.errors).forEach(([e, m]) => {
// Error response would be:
// image.0 => ['error message']
// ...
// video.3 => ['error message']
var errorIndex = parseInt(e.split('.')[1])
// image.0 > ["image", "0"]
errorMsg = m[0]
// Since we stored all previous selected files in an array
console.log(`Error in file index: ${errorIndex}, file name: ${this.upload.files[errorIndex].name}`)
console.log(`Error message: ${errorMsg}`)
// Error in file index [X], file name: hello_there.mp4
// Error: video.X size cannot be more than ... kilobytes (500Mb)
})
但问题是,我只想用拉威尔的方式来做
问:如何设置视频的最大大小?
提前感谢试试这个=>
public function upload(Request $request) {
$request->validate([
'file.*' => ['required', 'file', 'mimes:jpg,jpeg,png', 'max:2048'],
'file.mp4' => ['required', 'file', 'mimes:mp4', 'max:512000'] // 500 Mb for video/
]);
}
您可以根据文件mime类型进行验证,如以下psudo代码:
public function upload(Request $request) {
$rules = [];
$image_max_size = 1024 * 2;
$video_max_size = 1024 * 500;
foreach($request->file('file') as $index => $file){
if(in_array($file->getMimeType(), ['image/jpg', 'image/jpeg', 'image/png']) {
$rules["file.$index"] = ["max:$image_max_size"];
} else if (in_array($file->getMimeType(), ['video/mp4']){
$rules["file.$index"] = ["max:$video_max_size"];
} else {
// Always non-validating => returns error
$rules["file.$index"] = ['bail', 'mimes:jpg,jpeg,png,mp4'];
}
}
$request->validate($rules);
...
}
我也遇到过类似的问题,并用这种方法解决了这个问题。最好的方法是创建自己的验证规则,假设您使用的是laravel 8:@ChristianDelviantosimplest way:传递一个标志(如image=>1、video=>2等)。然后根据flag添加规则。其他选项:(1.)添加验证后挂钩->猜测mimetype->基于mimetype验证大小。(2.)创建自己的验证规则。它可以是图像或视频,对吗?如果是,则只需添加图像和视频质询更新的条件验证HI,感谢您的回答,但您的解决方案不起作用抱歉,我的答复不在rn区域,我明天将测试您的代码,稍后再告诉结果,无论如何,感谢您尝试帮助我解决问题接受、测试和编辑。
public function upload(Request $request) {
$rules = [];
$image_max_size = 1024 * 2;
$video_max_size = 1024 * 500;
foreach($request->file('file') as $index => $file){
if(in_array($file->getMimeType(), ['image/jpg', 'image/jpeg', 'image/png']) {
$rules["file.$index"] = ["max:$image_max_size"];
} else if (in_array($file->getMimeType(), ['video/mp4']){
$rules["file.$index"] = ["max:$video_max_size"];
} else {
// Always non-validating => returns error
$rules["file.$index"] = ['bail', 'mimes:jpg,jpeg,png,mp4'];
}
}
$request->validate($rules);
...
}