最近的項目用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拓展加進來
我改一步以後就就行了。對象