Symfony forms. File upload

一个人想着一个人 提交于 2019-12-22 00:00:09

问题


Trying to manage file upload with Entity, but i get this error:

Fatal error: Call to a member function move() on a non-object in /home/projectpath/src/BS/MyBundle/Entity/Items.php on line 327 Call Stack: 0.0002 333264 1. {main}() /home/projectpath/web/app_dev.php:0 0.0450 1158160...

Here's the entity class:

namespace BS\BackstretcherBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;

/**
* MB\MyBundle\Entity\Items
*
* @ORM\Table(name="items")
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Items
{
    private $filenameForRemove;

    /**
     * @Assert\File(maxSize="60000000")
     */
    public $file;
    ...

    protected function getUploadDir()
    {
       return 'images/items/';
    }

    protected function getUploadRootDir()
    {
      return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    public function getWebPath()
    {
      return null === $this->file ? null : $this->getUploadDir().'/'.$this->getNameEn();
    }

    public function getAbsolutePath()
    {
      return null === $this->file ? null : $this->getUploadRootDir().'/'.$this->getNameEn().'.jpg';
    }

  /**
   * @ORM\PrePersist()
   * @ORM\PreUpdate()
   */
    public function preUpload()
    {
      if (null !== $this->file)
      {
         $this->file = $this->getId() .'.'. $this->file->guessExtension();
      }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
      if (null === $this->file)
      {
        return;
      }

      $this->file->move($this->getUploadRootDir(), $this->file);
      unset($this->file);
    }

    /**
     * @ORM\PostRemove()
     */
     public function removeUpload()
     {
       if ($file = $this->getAbsolutePath())
       {
         unlink($file);
       }
     }

And the controller:

public function new_productAction(Request $request)
{
  $product = new Items();
  $product->setPrice(0);

  $form = $this->createFormBuilder($product)
    ->add('Type', 'choice', array(
      'choices'   => array('1' => 'Product', '0' => 'Article'),
      'required'  => false,))
    ->add('Price',  'number')
    ->add('nameEn', 'text')
    ->add('file', 'file', array('label' => 'Image', 'required' => true))
    ->getForm();

  if ($request->getMethod() == 'POST')
  {
    if ($form->isValid())
    {
      $form->bindRequest($request);
      $em = $this->getDoctrine()->getEntityManager();
      $em->persist($product);
      $em->flush();

      return new Response('<html><body>Success!</body></html>');
    }
  }

  return $this->render('MyBundle:Default:admin_page.html.twig', array(
    'form' => $form->createView(),
  ));
}

Symfony version: 2.1.0


回答1:


Check your php.ini file and make sure both the post_max_size AND upload_max_filesize are set sufficiently large.




回答2:


I don't suppose duke_nukem is worried about this anymore, 6 months down the line, but if someone else comes across this question, I was having the exact same problem and got a great answer to it here:

Error with file upload in symfony 2

Looks like duke_nukem and I made the same mistake. The preUpload() method should read:

  /**
   * @ORM\PrePersist()
   * @ORM\PreUpdate()
   */
    public function preUpload()
    {
      if (null !== $this->file)
      {
         $this->path = $this->getId() .'.'. $this->file->guessExtension();
      }
    }

The present code converts $this->file to a string, causing the error. The path should actually be assigned to $this->path.

Sybio in the other question figured this out, not me. I just want to spread the love.




回答3:


it's weird

your code is wrong in your controller. You have to bind your request to your form before validation. After that, you can retrieve your data

if ($request->getMethod() == 'POST')
  {
    //Note: bindRequest is now deprecated
    $form->bind($request);
    if ($form->isValid())
    {
      //retrieve your model hydrated with your form values
      $product = $form->getData();

      //has upload file ?
      if($product->getFile() instanceof UploadedFile){
        //you can do your upload logic here wihtout doctrine event if you want
      }

      $em = $this->getDoctrine()->getEntityManager();
      $em->persist($product);
      $em->flush();

      return new Response('<html><body>Success!</body></html>');
    }
  }


来源:https://stackoverflow.com/questions/11704525/symfony-forms-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!