图片必须是图片

时间:2020-07-21 05:18:58

标签: php laravel web file-upload frameworks

就这样。 我想编辑数据库中的数据,如果我每次填写表格时都上传图像,则可以很好地工作。但是当我编辑另一个数据并且不上传图像而不是用来自数据库的旧图像数据(这是本地文件)填充图像时,就会出现问题。图片验证会引发错误。

这里我的图像验证 'image' => 'image|max:1024'

如果我像这样'image' => 'max:1024'放它,它将运行良好,因为它不会检查它是否是图像,但是它将产生一个问题,用户开始使用编辑数据功能来注入另一个不需要的代码。

这是更新代码

use WithFileUploads;

public $productId;
public $title;
public $description;
public $price;
public $image;
public $imageOld;

protected $listeners = [
    'editProduct' => 'editProductHandler'
];

public function update()
    {
        $this->validate([
            'title' => 'required|min:3',
            'price' => 'required|numeric',
            'description' => 'required|max:180',
            'image' => 'image|max:1024'
        ]);

        if ($this->productId) {
            $product = Product::find($this->productId);

            $image = '';

            if ($this->image) {
                Storage::disk('public')->delete($product->image);

                $imageName = \Str::slug($this->title, '-')
                    . '-'
                    . uniqid()
                    . '.' . $this->image->getClientOriginalExtension();
            
                $this->image->storeAs('public', $imageName, 'local');

                $image = $imageName;
            } else {
                $image = $product->image;
            }

            $product->update([
                'title' => $this->title,
                'price' => $this->price,
                'description' => $this->description,
                'image' => $image
            ]);

            $this->emit('productUpdated');
        }
    }

0 个答案:

没有答案