首页 > 解决方案 > 在 symfony 3 中使用 html 表单上传图片

问题描述

我正在使用 symfony 3.4,我正在尝试使用 HTML 表单上传图像。当我选择图像并提交表单时,我收到此错误:“调用字符串上的成员函数 move()”

这是我的 html.twig 文件(表单部分):

 <form role="form" id="contact_form" class="contact-form" method="post" action="{{ path('publier_offre') }}" enctype="multipart/form-data">
 <input type="file" class="form-control" name="" id="imageOffre">                                         
                        </form>

这是控制器操作(从哪里获取上传的图像并将其保存到数据库):

 public function publierOffreAction(Request $request)
    {
        if($request->isMethod('POST')){
            $offre = new offre();
            //getting the image file
            $filename = $request->files->get('imageOffre');
            $filename->move(
                $this->getParameter('image_directory'),$filename
            );
            $offre->setImage($filename);
            //getting the image file
            $em=$this->getDoctrine()->getManager();
            $em->merge($offre);
            $em->flush();
        }
        return $this->render('@offer/Default/publieroffre.html.twig');
    }

这是我的实体文件 offer.php 中的图像属性:

    /**
     * @var string
     * @Assert\NotBlank(message="plz enter an image")
     * @Assert\Image()
     * @ORM\Column(name="image", type="string", length=255)
     */
    private $image ;  

 /**
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * @param string $image
     */
    public function setImage($image)
    {
        $this->image = $image;
    }

这是默认上传目录( config.yml ):

parameters:
    locale: en
    image_directory: '%kernel.project_dir%/web/uploads/images'

我建议我没有在控制器中以正确的方式获取上传的图像。请帮忙,谢谢

标签: phphtmlsymfony

解决方案


推荐阅读