Laravel验证不适用于文件数组


Laravel validation not working with array of files

我正在向Laravel提交一组文件字段,我想对每个文件进行验证,以检查它是否是正确的mime类型(只允许使用PNG、JPG和GIF)。但是,如果我上传了TIF图像文件,则验证通过。以下是我提交的内容:

Request URL:http://local.website.com/upload
Request Method:POST
Status Code:200 OK
Remote Address:127.0.0.1:80
Response Headers
view source
Connection:Keep-Alive
Content-Length:6
Content-Type:text/html; charset=UTF-8
Date:Mon, 02 May 2016 19:05:18 GMT
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3
X-Powered-By:PHP/5.6.3
Request Headers
view source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:19912006
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarypWGUvcecHBZlzNcP
Cookie:__utma=252126427.1839499577.1452033482.1452033483.1452072866.2; __utmz=252126427.1452033483.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _gat=1; _ga=GA1.2.1839499577.1452033482; laravel_session=eyJpdiI6InVxazdLSFwvNWNRUnl2eDQrRmFhdUpBPT0iLCJ2YWx1ZSI6IlJRXC9mRk9EYXBUWUpQMHpFMms3Mm9hYkRiekNjUlJHTDlBS0hpYkk2R091RmFYQzVsM1JWcEdMdmFzRjl3Q3BoaEZHQUM3VFc5ZE5Oak5KdHowaU0zdz09IiwibWFjIjoiZTYxM2U3MmVhNzU4NmFiZDNmYWFhNjdiZDE3NDczM2IxN2RmYWFhYWZlMzhiNTBiM2IwZjEyYWQwNThhMTk1MyJ9
Host:local.website.com
Origin:http://local.website.com
Pragma:no-cache
Referer:http://local.website.com/
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
------WebKitFormBoundarypWGUvcecHBZlzNcP
Content-Disposition: form-data; name="files[]"; filename="eye design.png"
Content-Type: image/png

------WebKitFormBoundarypWGUvcecHBZlzNcP
Content-Disposition: form-data; name="files[]"; filename="hd flamingo.tif"
Content-Type: image/tiff

------WebKitFormBoundarypWGUvcecHBZlzNcP
Content-Disposition: form-data; name="files[]"; filename="Picture 3.tif"
Content-Type: image/tiff

------WebKitFormBoundarypWGUvcecHBZlzNcP
Content-Disposition: form-data; name="files[]"; filename="Picture 16.tif"
Content-Type: image/tiff

------WebKitFormBoundarypWGUvcecHBZlzNcP
Content-Disposition: form-data; name="files[]"; filename="Picture 23.tif"
Content-Type: image/tiff

------WebKitFormBoundarypWGUvcecHBZlzNcP--

以下是我请求的内容:

<?php namespace App'Http'Requests;
use Response;
use Illuminate'Foundation'Http'FormRequest;
class UploadRequest extends FormRequest
{
    public function rules()
    {
        $rules = [
            'files' => 'required'
        ];
        foreach($this->files as $key => $file) {
            $rules['files.'.$key] = 'image|mimes:jpeg,png,gif';
        }
        return $rules;
    }
    public function messages()
    {
        $messages = [
            'files.required' => 'You must upload a file.'
        ];
        foreach($this->files as $key => $file) {
            $messages['files.'.$key.'.image'] = 'The upload file must be an image.';
            $messages['files.'.$key.'.mimes'] = 'The image must be one of the following types: JPEG, PNG, or GIF.';
        }
        return $messages;
    }
    public function authorize()
    {
        return true;
    }
}

这是我提交表格的路线:

Route::post('upload', ['uses' => 'UploadController@index', 'as' => 'upload.post']);

这是我的UploadController文件:

<?php namespace App'Http'Controllers;
use Response;
use Illuminate'Http'Request;
use Input;
use Image;
use Session;
use App'Http'Requests'UploadRequest;
use Auth;
use App'Setting;
use App'Discount;
use App'User_credit;
use App'Customer_group_discount;
use Event;
use App'Events'ImagesUpdated;
class UploadController extends Controller {
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
    }
    /**
     * Handles the uploading of images
     *
     * @return Response json
     */
    public function index(UploadRequest $request)
    {
        // validation has passed do stuff
    }
}

请求肯定在运行,但它在应该运行的时候并没有失败。我做错了什么?

我最终解决了它,现在是我的请求:

<?php namespace App'Http'Requests;
use Response;
use Illuminate'Foundation'Http'FormRequest;
class UploadRequest extends FormRequest
{
    public function rules()
    {
        $request = $this->instance()->all();
        $images = $request['files'];
        $rules = [
            'files' => 'required'
        ];
        foreach($images as $key => $file) {
            $rules['files.'.$key] = 'image|mimes:jpeg,png,gif';
        }
        return $rules;
    }
    public function messages()
    {
        $request = $this->instance()->all();
        $images = $request['files'];
        $messages = [
            'files.required' => 'You must upload a file.'
        ];
        foreach($images as $key => $file) {
            $messages['files.'.$key.'.image'] = 'The upload file must be an image.';
            $messages['files.'.$key.'.mimes'] = 'The image must be one of the following types: JPEG, PNG, or GIF.';
        }
        return $messages;
    }
    public function authorize()
    {
        return true;
    }
    public function response(array $errors)
    {
        $request = $this->instance()->all();
        $images = $request['files'];
        $image = $images[0];
        $error_string = '';
        foreach($errors['files.0'] as $error) {
            $error_string.= ' '.$error;
        }
        $json = array('files' => array(
            array(
                'name' => $image->getClientOriginalName(),
                "size" => $image->getClientSize(),
                'error' => $error_string
            )
        ));
        return Response::json($json);
    }
}

由于某些原因,使用自定义请求执行验证时,Laravel不包括上传的文件。解决这个问题的第一种方法是使用手动验证器,如Laravel 4中所述。

另一种方法是将上传的文件包含在请求中。在您的扩展请求类中,添加以下内容:

// 'massage' data so that files get in as well
protected function getValidatorInstance()
{
    $data = $this->all();
    $data['logo'] = $this->file('project_logo'); 
    $data['banner'] = $this->file('project_banner');
    $this->getInputSource()->replace($data);
    return parent::getValidatorInstance();
}

代码所做的是覆盖请求的getValidatorInstance()方法,并手动将文件放入其中。在这种情况下,我有两个文件需要验证,它们在HTML表单中的名称分别为project_logoproject_banner

这不是一个确切的解决方案,而是一个检查文件的简单方法。

if($request->file('docs')) {
$extensions_allowed = ['pdf', 'docx'];
foreach ($request->file('docs') as $file) {
   if(in_array($file->getClientOriginalExtension('docs'), $extensions_allowed)){
        return "yes----";
    }else {
       return "No-----";
    }
  }
}