【发布时间】:2021-09-20 12:57:04
【问题描述】:
我正在验证多个图像,但验证不起作用。我用谷歌搜索了很多,但没有答案对我有用。我被卡住了。
这是代码(刀片文件):
<div class="form-row mb-4 d-none">
<input type="file" name="images[]" class="form-control adForm-fileInput d-none" multiple />
</div>
{{-- Triggering the input file --}}
<button type="button" class="btn btn-light adForm-uploadBtn mb-4">
Upload Images
</button>
控制器
public function store(Request $request)
{
$request->validate([
// ...
'images' => 'required',
'images.*' => 'image|mimes:jpeg,png,jpg|max:2048',
// ...
]);
// ... All Inputs requests
$files = [];
if ($request->hasfile('images')) {
$images = $request->file('images');
foreach ($images as $image) {
$name = Str::random(30) . $image->getClientOriginalName();
$image->move(public_path().'/uploads/', $name);
$files[] = $name;
}
}
$files = json_encode($files);
// Ads::insert();
return redirect()->back()->with('success', 'Your ad has been created!');
}
我正在上传 jpg 图片,但出现此错误:
The images.0 must be a file of type: jpeg, png, jpg.
The images.1 must be a file of type: jpeg, png, jpg.
The images.2 must be a file of type: jpeg, png, jpg.
The images.3 must be a file of type: jpeg, png, jpg.
我的表格:
<form action="{{ route('routeName') }}" method="post" enctype="multipart/form-data" class="adForm">
@csrf
//...
不应该产生错误,因为我正在上传jpg/png 图像并且错误应该在 1 行,它在重复。请帮我弄清楚。我被卡住了
【问题讨论】:
-
乍一看,您的代码没有任何问题,您的表单到底是什么样的?您是否将
enctype='multipart/form-data'添加到 HTML 中的开始表单标记中? -
是的,它已经添加到我的表单中。我也对此感到困惑,它应该工作,但它不工作
-
我已经重新创建了你的代码,对我来说它正在工作。如果您上传
png或其他可接受的文件类型会怎样?当您完全删除 mime 类型时会发生什么?也许您可以在您的问题中分享您的整个表格,以便我们检查这是否导致任何错误? -
确保您的表单方法不是 GET
-
我通过将 mimetype 更改为 mime 并添加可为空来解决此问题。 $this->validate([ 'media.*' => 'nullable|mimes:jpeg,png,jpg,gif,svg,bmp,mp4,avi,mpg,mpeg|max:'.(1024*250), ] );
标签: php laravel validation eloquent