最近的項目用laravel-admin做開發,版本是1.8.11,發現了一個圖片上傳的問題,搜了一下好多人也遇到但是也沒什麼人貼解決方案,貼一下我的解決方法。
我遇到的問題就是:
添加一條記錄的時候可以正常添加,圖片也能正常保存。第二次要修改這條記錄時,無論改沒改這個圖片,都無法保存。彈出來的錯誤提示是
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
大概就是説需要傳一個對象,卻給了字符串。
一看到是在encore裏面報出來的錯誤,但是我的代碼很簡單,不太可能是調用出了問題。另外有很多人在論壇上吐槽這個問題,所以我估計這是一個bug.
$form->UEditor('title','標題');
$form->image('logo', '圖標');
$form->UEditor('content', '內容');
$form->number('order', '排序');
$form->text('typesetting', '佈局');
解決方法其實説出來也挺無奈的
- 1.降低版本 辦公室的同事一個是1.7 一個是1.4 他們沒有出現過個bug
- 2.自己寫一個image拓展
寫拓展之前首先要解決掉這個bug 我找到源碼裏面的image.php,給報錯的地方加了個is_string的判斷。
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這個拓展是有其他依賴的,所以也要確保依賴引入是正確的。改完如下:
<?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改一下配置
Form::forget(['map', 'editor','image']);//原來的image加入到forget裏面
Form::extend('image', AppAdminExtensionFormImage::class);//自己改過的image拓展加進來
我改一步之後就就好了。