代码之家  ›  专栏  ›  技术社区  ›  Jim

Laravel背包未上传图像

  •  0
  • Jim  · 技术社区  · 7 年前

    我试图上传一个文件(国旗)到一个简单的表国家,应该保存在一个“国旗”文件夹的公共。

    在我的addfield声明中

    $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 回复  |  直到 7 年前
        1
  •  0
  •   tabacitu    7 年前

    你应该再看一眼 这个 instructions for the image field type ,在文件中。背包不负责为您上传- 您的模型上需要一个访问器 ,因此您可以选择上载位置和方式。如果您不这样做,Backpack将尝试将其作为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;
        }
    }
    
    推荐文章