我试着验证图像,所以用户应该只输入五个图像(最多),他也不应该能够上传视频,ai,psd等。到目前为止,当我试图上传一个视频,它没有显示错误,它没有上传产品,如果我试图上传其他文件,如psd,它会显示一个错误。
照明\ Http \Exception\ PostTooLargeException
如何仅验证要上载的五个图像(最多)以及这些类型的文件( mimes:jpeg,jpg,png )
代码
控制器
public function store(Request $request)
{
$this->validate(
$request,
[
'photos' => 'required',
'photos.*' => '|mimes:jpeg,jpg,png',
]);
foreach ($request->photos as $photo) {
$filename = $photo->store('public/photos');
ProductsPhoto::create([
'product_id' => $product->id,
'filename' => $filename
]);
}
}叶片模板
<input multiple="multiple" name="photos[]" type="file">发布于 2019-07-13 23:58:43
如果我试图上传像psd这样的其他文件,它会显示一个错误
Illuminate\Http\Exceptions\PostTooLargeException。
当有效负载高于服务器配置的PostTooLargeException时(当然,您可以自定义这一点),就会抛出PostTooLargeException。例如,如果用户试图上传视频,则始终会引发这种情况。现在,您可以以不同的方式来处理这个问题(而不是排他的):
对于后一个选项,您可以使用最大值规则,该规则遵循对大小验证规则的验证。从医生那里:
最大值:价值 被验证的字段必须小于或等于最大值。字符串、数字、数组和文件的计算方式与大小规则相同。 大小:价值 验证中的字段必须具有与给定值匹配的大小。对于字符串数据,值对应于字符数。对于数字数据,值对应于给定的整数值。对于数组,大小对应于数组
count的。对于文件,大小对应于文件大小(以千字节为单位).。
因此,在您的情况下,您可以检查上传的文件:
$this->validate(
$request,
[
'photos' => 'required',
'photos.*' => 'mimes:jpeg,jpg,png|max:4000', // e.g., each file should be less than 4MB
)];与下一个事项有关:
如何才能验证只上传五个图片(最多)?
您可以使用相同的规则,但现在可以验证数组大小:
$this->validate(
$request,
[
'photos' => 'required|array|max:5', // <----
'photos.*' => 'mimes:jpeg,jpg,png',
)];当然,您可以结合这些限制来完成您想要的行为。
发布于 2019-07-14 06:44:23
很简单,我之前已经做过了:
$galleryImageCount = 0; // count the number of existing images if needed
$galleryImageRules = ['bail|image|mimes:jpeg,png,jpg|max:5120','bail|sometimes|image|mimes:jpeg,png,jpg|max:5120'];
$imageRule = [];
for ($i = 0; $i < (5 - $galleryImageCount); $i++) {
$rule = ($i == 0) ? $galleryImageRules[0] : $galleryImageRules[1];
$key = 'gallery_image.' . $i;
$imageRule[$key] = $rule;
}
$this->validate(
$request,
$imageRule);
//Replace 'gallery_image' with 'photos' in your case.https://stackoverflow.com/questions/57023354
复制相似问题