关于laravel:laraveladmin的图片上传bug

15次阅读

共计 2233 个字符,预计需要花费 6 分钟才能阅读完成。

最近的我的项目用 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 拓展加进来

我改一步之后就就好了。

正文完
 0