一、解决办法:
使用laravel内置的文件上传验证Request。
有时候,上传EXCEL时,虽然MIMES类型已经增加,但是验证就不通过,最后在mimes类型里增加了bin类型才解决。
1、最终验证Code:
<?php
namespace Modules\Finance\Http\Requests\MerchantsSettlement;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use App\Exceptions\APIHttpException;
class AttachmentRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
/*上传文件*/
'file' => 'bail|required|file|min:1|max:102400|mimes:png,jpg,gif,jpeg,pdf,zip,rar,doc,docx,bin,xls,xlsx,ppt,pptx',
'merchant_id' => 'bail|required|numeric',
'period' => 'bail|required',
];
}
public function messages()
{
return [
'required' => ':attribute不能为空',
'numeric' => ':attribute必须是数字',
'file' => ':attribute必须是文件',
'mimes' => '文件格式不合法~',
'max' => '文件大小超出100M限制~',
];
}
public function attributes()
{
return [
'file' => '上传',
'merchant_id' => '商户ID',
'period' => '结算期间',
];
}
public function failedValidation(Validator $validator)
{
throw new APIHttpException($validator->errors()->first());
}
}
二、问题定位:
1、查看laravel版本
?2、在项目根目录调试该文件
vim vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php
/**
* Validate the guessed extension of a file upload is in a set of file extensions.
*
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @return bool
*/
public function validateMimes($attribute, $value, $parameters)
{
if (! $this->isValidFileInstance($value)) {
return false;
}
if ($this->shouldBlockPhpUpload($value, $parameters)) {
return false;
}
return $value->getPath() !== '' && in_array($value->guessExtension(), $parameters);
}
大概在1188行,具体可以,在该方法里使用echo、var_dump()方法进行定位和调试即可。
|