编辑:警告!这个答案适用于我的 XAMPP OsX 环境,但是当我将它部署到 AWS EC2 时,它并没有阻止上传尝试。
我很想删除这个答案,因为它是错误的,但是我会解释是什么让我绊倒了
我的文件上传字段名为“上传”,所以我收到“上传失败。”。此消息来自validation.php 中的这一行:
在资源/lang/en/validaton.php:
'uploaded' => 'The :attribute failed to upload.',
这是当文件大于 PHP 设置的限制时显示的消息。
我想覆盖这条消息,通常可以通过将第三个参数 $messages 数组传递给 Validator::make() 方法来实现。
但是我不能这样做,因为我从 React 组件调用 POST,它会呈现包含 csrf 字段和上传字段的表单。
因此,作为一个超级狡猾的黑客,我选择进入显示消息的视图并将该特定消息替换为我友好的“文件太大”消息。
如果文件小于 PHP 文件大小限制,以下是可行的:
如果其他人使用 Laravel FormRequest 类,以下是在 Laravel 5.7 上对我有用的方法:
这是我设置自定义错误消息和最大文件大小的方式:
我有一个输入字段<input type="file" name="upload">。请注意,CSRF 令牌在表单中也是必需的(google laravel csrf_field 是什么意思)。
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
...
...
public function rules() {
return [
'upload' => 'required|file|max:8192',
];
}
public function messages()
{
return [
'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
];
}
}