我有以下代码:
use Illuminate\Support\Facades\Validator;
$rules = array(
'attachment' => 'max:1000|file|mimes:jpeg,png,jpg,gif,svg,pdf',
);
$messages = array(
'attachment.max' => 'max error',
'attachment.file' => 'file error',
'attachment.mimes' => 'mimes error',
//'attachment' => 'all errors',
);
$validator = Validator::make($this->request->all(), $rules, $messages);
我正在尝试应用“指定自定义属性值”的概念: https://laravel.com/docs/9.x/validation#specifying-custom-attribute-values
我正在使用 Laravel:
"laravel/framework": "^9.19"
但是不行,没有根据具体错误识别消息,显示如下:
dd($validator->messages());
Illuminate\Support\MessageBag {#1547
#messages: array:1 [
"attachment" => array:1 [
0 => "The attachment failed to upload."
]
]
#format: ":message"
}
错误在哪里?谁能帮助我并向我解释这种行为的原因?
我想对每种类型的错误使用特定的消息,我不想取消注释
//'attachment'
并且无法控制上传失败的位置。
我设法找到了上述问题的原因。
事实上,问题不在这段代码中,而是在我发送到服务器的文件中,由于某种原因,Laravel/PHP 无法检索重要信息以正确验证,如下所示:
在正确的场景中,它按我的预期工作,服务器打印输出是: (请注意,Laravel 成功获取了
size
和其他值)
Illuminate\Http\UploadedFile {#1523 // app/Validators/OrderFileValidator.php:58
-test: false
-originalName: "2023-11-12 09-17-00.mp4"
-mimeType: "video/mp4"
-error: 0
#hashName: null
path: "/tmp"
filename: "phpsItJmi"
basename: "phpsItJmi"
pathname: "/tmp/phpsItJmi"
extension: ""
realPath: "/tmp/phpsItJmi"
aTime: 2024-02-12 10:33:26
mTime: 2024-02-12 10:33:26
cTime: 2024-02-12 10:33:26
inode: 3805560
size: 1906989
perms: 0100600
owner: 33
group: 33
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
}
Illuminate\Support\MessageBag {#1547
#messages: array:1 [
"attachment" => array:2 [
0 => "The maximum file size is 1 mb (megabyte)"
1 => "The extensions allowed for the file are: jpeg,png,jpg,gif,svg,pdf"
]
]
#format: ":message"
}
现在,对于无效文件(打开此问题的原因),Laravel/PHP 读取以下值: (注意它无法获取文件大小和其他几个属性)
Illuminate\Http\UploadedFile {#1523 // app/Validators/OrderFileValidator.php:58
-test: false
-originalName: "Presentation - José Victor_20240125_070758_0000.pdf"
-mimeType: "application/octet-stream"
-error: 1
#hashName: null
path: ""
filename: ""
basename: ""
pathname: ""
extension: ""
realPath: "/var/www/html/app/public"
aTime: 1969-12-31 21:00:00
mTime: 1969-12-31 21:00:00
cTime: 1969-12-31 21:00:00
inode: false
size: false
perms: 00
owner: false
group: false
type: false
writable: false
readable: false
executable: false
file: false
dir: false
link: false
}
dd($_FILES);
array:1 [
"attachment" => array:5 [
"name" => "Presentation - José Victor_20240125_070758_0000.pdf"
"type" => ""
"tmp_name" => ""
"error" => 1
"size" => 0
]
]
这也是我用来发送文件的表格:
<form action="http://localhost:8080/app/public/..." method="POST" enctype="multipart/form-data">
<input type="file" class="form-control" name="attachment" required="">
...
</form>
我唯一的问题是:现在怎么办? PHP 读取一个文件而不读取另一个文件的标准是什么?
是否有一个 PHP 配置文件可以限制这样的事情?