在Symfony上上传图像时出现问题


issue uploading image on symfony

   /**
    * Upload the image while creating/updating records
    * @param File Object $file
    */
    public function setImageAttribute($file)
    {
        // Only if a file is selected
        if ($file) {
            File::exists(public_path() . '/uploads/') || File::makeDirectory(public_path() . '/uploads/');
            File::exists(public_path() . '/' . $this->images_path) || File::makeDirectory(public_path() . '/' . $this->images_path);
            File::exists(public_path() . '/' . $this->thumbs_path) || File::makeDirectory(public_path() . '/' . $this->thumbs_path);
            $file_name = $file->getClientOriginalName();
            $image = Image::make($file->getRealPath());
            if (isset($this->attributes['image'])) {
                // Delete old image
                $old_image = $this->getImageAttribute();
                File::exists($old_image) && File::delete($old_image);
            }
            if (isset($this->attributes['thumb'])) {
                // Delete old thumbnail
                $old_thumb = $this->getThumbAttribute();
                File::exists($old_thumb) && File::delete($old_thumb);
            }
            $image->save($this->images_path . $file_name)
                  ->fit(640, 180)
                  ->save($this->thumbs_path . $file_name);
            $this->attributes['image'] = $file_name;
        }
    }

这是我的错误消息

production.ERROR: exception 'Symfony'Component'Debug'Exception'FatalErrorException' with message 'Call to a member function getClientOriginalName() on a non-object' in C:'Doptor'app'components'posts'models'Post.php:79

79号线在这里

$file_name = $file->getClientOriginalName();
$image = Image::make($file->getRealPath());

在食谱中查看此条目,因为我认为您将更容易直接使用 Doctrine 上传您的图像。

其次,您还可以通过检查以下内容来探测您的$file是否是正确的对象:

if ($file instanceof UploadedFile) {
  // do stuff
} else {
 exit("file is not the right object, so getClientOriginalName will not work");
}