Laravel 5 验证有效文件类型的 csv 文件错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29159933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:10:24  来源:igfitidea点击:

Laravel 5 validate csv file error on valid file type

phpvalidationcsvlaravel

提问by Swaraj Giri

I am trying to validate an uploaded csv file with

我正在尝试验证上传的 csv 文件

$validator = Validator::make(
        [
            'file'      => $file,
            'extension' => strtolower($file->getMimeType()),
        ],
        [
            'file'      => 'required|in:csv',
        ]
    );

The validator fails on giving a valid csv file with message The file must be a file of type: csv.

验证器无法提供带有消息的有效 csv 文件 The file must be a file of type: csv.

The validator passes if i remove in:csv.

如果我删除in:csv.

Am i doing something wrong?

难道我做错了什么?

PS - $fileis available and of standard upload file type object(Symfony\Component\HttpFoundation\File\UploadedFile)

PS -$file可用且标准上传文件类型object(Symfony\Component\HttpFoundation\File\UploadedFile)

回答by Chris Townsend

Try changing

尝试改变

$validator = Validator::make(
    [
        'file'      => $file,
        'extension' => strtolower($file->getMimeType()),
    ],
    [
        'file'      => 'required|in:csv',
    ]
);

To

$validator = Validator::make(
    [
        'file'      => $file,
        'extension' => strtolower($file->getClientOriginalExtension()),
    ],
    [
        'file'          => 'required',
        'extension'      => 'required|in:csv',
    ]
);

回答by Ivanka Todorova

If you're uploading a CSV file, you should allow the following mime types:

如果您要上传 CSV 文件,则应允许以下 MIME 类型:

'application/vnd.ms-excel','text/plain','text/csv','text/tsv'

Also in Laravel 5:

同样在 Laravel 5 中:

$rules =  [
    'file'          => 'required',
    'extension'      => 'required|mimes:csv'
];

From the docs: (http://laravel.com/docs/5.0/validation)

来自文档:(http://laravel.com/docs/5.0/validation

The Validator class provides several rules for validating files, such as size, mimes, and others. When validating files, you may simply pass them into the validator with your other data.

Validator 类提供了一些用于验证文件的规则,例如sizemimes等。验证文件时,您可以简单地将它们与其他数据一起传递到验证器中。