最近的项目用laravel-admin作开发,版本是1.8.11,发现了一个图片上传的问题,搜了一下好多人也遇到可是也没什么人贴解决方案,贴一下个人解决方法。
我遇到的问题就是:php
添加一条记录的时候能够正常添加,图片也能正常保存。第二次要修改这条记录时,不管改没改这个图片,都没法保存。弹出来的错误提示是laravel
Argument 1 passed to Encore\Admin\Form\Field\File::getStoreName() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, null given, called in XXXX\vendor\encore\laravel-admin\src\Form\Field\Image.php on line XXX
大概就是说须要传一个对象,却给了字符串。bootstrap
一看到是在encore里面报出来的错误,可是个人代码很简单,不太多是调用出了问题。另外有不少人在论坛上吐槽这个问题,因此我估计这是一个bug.布局
$form->UEditor('title','标题'); $form->image('logo', '图标'); $form->UEditor('content', '内容'); $form->number('order', '排序'); $form->text('typesetting', '布局');
解决方法其实说出来也挺无奈的this
写拓展以前首先要解决掉这个bug 我找到源码里面的image.php,给报错的地方加了个is_string的判断。spa
if(!is_string($image)){ $this->name = $this->getStoreName($image); $this->callInterventionMethods($image->getRealPath()); $path = $this->uploadAndDeleteOriginal($image); $this->uploadAndDeleteOriginalThumbnail($image); return $path; }else{ return $image; }
运行以后没有问题 接着就是拓展了
复制整个文件Image.php,而后我把它放到App\Extension\Form下面,由于我加过uEditor的拓展,因此有这个目录,没有的能够本身建。
放进去以后改一下namespace和use 由于Image这个拓展是有其余依赖的,因此也要确保依赖引入是正确的。改完以下:code
<?php namespace App\Admin\Extension\Form; use Encore\Admin\Form\Field\File; use Encore\Admin\Form\Field\ImageField; use Symfony\Component\Http\Foundation\File\UploadedFile; class Image extends File { use ImageField; /** * {@inheritdoc} */ protected $view = 'admin::form.file'; /** * Validation rules. * * @var string */ protected $rules = 'image'; /** * @param array|UploadedFile $image * * @return string */ public function prepare($image) { if ($this->picker) { return parent::prepare($image); } if (request()->has(static::FILE_DELETE_FLAG)) { return $this->destroy(); } if(!is_string($image)){ $this->name = $this->getStoreName($image); $this->callInterventionMethods($image->getRealPath()); $path = $this->uploadAndDeleteOriginal($image); $this->uploadAndDeleteOriginalThumbnail($image); return $path; }else{ return $image; } } /** * force file type to image. * * @param $file * * @return array|bool|int[]|string[] */ public function guessPreviewType($file) { $extra = parent::guessPreviewType($file); $extra['type'] = 'image'; return $extra; } }
接着App\Admin\bootstrap.php改一下配置orm
Form::forget(['map', 'editor','image']);//原来的image加入到forget里面 Form::extend('image', AppAdminExtensionFormImage::class);//本身改过的image拓展加进来
我改一步以后就就行了。对象