【发布时间】:2016-01-31 19:14:35
【问题描述】:
我正在 Laravel 5 中创建一个表单,其中包含产品名称、产品主图像和次要图像。图像字段和辅助字段都是可选的。
<div class="form-group {{ ($errors->has('title')) ? 'has-error' : '' }}">
<label>Title *</label>
<input class="form-control validate[required]" name="title" type="text" value="{{ Input::old('title') }}">
{{ ($errors->has('title') ? $errors->first('title') : '') }}
</div>
<div class="form-group">
<label for="featured_image">Cover Image
<small>(optional)</small>
</label>
<input type="file" placeholder="" id="featured_image" name="featured_image">
<small class="description"> Maximum file size: 2 MB.</small>
{{ ($errors->has('title') ? $errors->first('featured_image') : '') }}
</div>
<div class="form-group">
<label for="gallery_images">Gallery Images
<small>(optional)</small>
</label>
<input type="file" placeholder="" id="gallery_images" name="gallery_images[]" multiple="">
<small class="description">Maximum file size: 2 MB.</small>
{{ ($errors->has('title') ? $errors->first('gallery_images') : '') }}
</div>
我在请求文件中的验证是:
public function rules()
{
return [
'title' => 'required|min:5',
'featured_image' => 'mimes:jpeg,png,jpg|max:2048',
'gallery_images' => 'mimes:jpeg,png,jpg|max:2048'
];
}
但它总是检查图片是否上传。这是不正确的,仅在上传图像时检查图像类型,否则不检查。
谢谢。
【问题讨论】:
-
因为在上传之前服务器没有关于图像的信息,脚本无法进行您想要的检查。解决此问题的最佳方法是使用在客户端上运行的 javascript 在上传前进行检查。
-
Alvin 我还想要服务器端验证,只有在上传任何内容时才必须检查图像类型。
-
但是你不能使用 $rules 验证选项
-
那你建议我怎么做?
-
无论是在客户端还是上传到 /tmp ,进行检查,如果失败则从 /tmp 中删除。但老实说,如果访问者上传了一个非常大的文件,并且在上传后他/她听到这是错误的格式怎么办。所以最好在客户端进行检查,而不是通过整个上传过程。查看答案如何轻松做到这一点...