Laravel背包未上传图像

时间:2018-11-25 08:46:41

标签: laravel-5 backpack-for-laravel

我正在尝试将文件(国家/地区标志)上传到简单的表格国家/地区,应将其保存在公共的“标志”文件夹中。

在我的添加字段声明中,我有

$this->crud->addField([ // image
          'label' => "flag",
          'name' => "flag",
          'type' => 'image',
          'upload' => true,
          'disk' => 'flags', // in case you need to show images from a different disk
          'prefix' => 'flags/'

在文件系统文件中,我有:

'flags' => [
        'driver' => 'local',
        'root' => public_path('flags'),
        'url' => '/flags',
        'visibility' => 'public',
    ],

当我上传时,它告诉我该字段太短了(它是varchar 255),因为它似乎想将文件存储为数据图像。

1 个答案:

答案 0 :(得分:0)

您应该再次查看文档中的instructions for the image field type all 。背包不会为您完成上传操作-您的模型需要访问器,因此您可以选择上传位置以及上传方式。如果您不这样做,背包将尝试将其作为Base64存储在数据库中-在大多数情况下,这不是一个好主意。

flag的访问器示例:

public function setFlagAttribute($value)
{
    $attribute_name = "flag";
    $disk = "public_folder";
    $destination_path = "uploads/folder_1/subfolder_3";

    // if the image was erased
    if ($value==null) {
        // delete the image from disk
        \Storage::disk($disk)->delete($this->{$attribute_name});

        // set null in the database column
        $this->attributes[$attribute_name] = null;
    }

    // if a base64 was sent, store it in the db
    if (starts_with($value, 'data:image'))
    {
        // 0. Make the image
        $image = \Image::make($value)->encode('jpg', 90);
        // 1. Generate a filename.
        $filename = md5($value.time()).'.jpg';
        // 2. Store the image on disk.
        \Storage::disk($disk)->put($destination_path.'/'.$filename, $image->stream());
        // 3. Save the path to the database
        $this->attributes[$attribute_name] = $destination_path.'/'.$filename;
    }
}