1

I'm trying to upload a file using my own form with symfony2. I get no errors, and the name of the file is correctly addeded on database, but the file is not uploaded.

here is my routing.yml :

upload_homepage:
    pattern:  /upload
    defaults: { _controller: UploadBundle:Default:index }
upload:
    pattern:  /upload/file
    defaults: { _controller: UploadBundle:Default:upload }

twig:

<form enctype="multipart/form-data" action="{{ path('upload') }}" method="POST">
    <input type="file" name="file">
    <input type="submit">
</form>

My controller :

<?php

namespace Upload\UploadBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

use Upload\UploadBundle\Entity\Document;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render('UploadBundle:Default:index.html.twig');
    }

    public function uploadAction(Request $request)
    {


        $em = $this->getDoctrine()->getManager();
        $document = new Document();
        $document->setChemain($request->files->get('file')->getClientOriginalName());
        //$document->upload();
        // print_r($request->files->get('file')->getClientOriginalName());
        // die();
        $em->persist($document);
        $em->flush();
        return new Response("Ok");
    }
}

The Entity:

<?php

namespace Upload\UploadBundle\Entity;

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

/**
 * Document
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Upload\UploadBundle\Entity\DocumentRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Document
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="chemain", type="string", length=255)
     */
    private $chemain;

    /**
     * @Assert\File(maxSize="6000000")
     * mimeTypes = {"image/jpg", "image/gif", "image/png", "image/tiff"},
     * maxSizeMessage = "The maxmimum allowed file size is 5MB.",
     * mimeTypesMessage = "Only the filetypes image are allowed."
     */
    public $file;
    /**
     * Get id
     *
     * @return integer 
     */

    // propriété utilisé temporairement pour la suppression
    private $filenameForRemove;

    public function getId()
    {
        return $this->id;
    }

    /**
     * Set chemain
     *
     * @param string $chemain
     * @return Document
     */
    public function setChemain($chemain)
    {
        $this->chemain = $chemain;

        return $this;
    }

    /**
     * Get chemain
     *
     * @return string 
     */
    public function getChemain()
    {
        return $this->chemain;
    }



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

    protected function getUploadRootDir()
    {

        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {

        return 'uploads';
    }

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

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

        try {
             $this->file->move($this->getUploadRootDir(), $this->id.'.'.$this->file->guessExtension());
             unset($this->file);
        } catch (FileException $e) {
            return $e;
        }

    }

    /**
     * @ORM\PreRemove()
     */
    public function storeFilenameForRemove()
    {
        $this->filenameForRemove = $this->getAbsolutePath();
    }

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

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

Any idea ?

4
  • see symfony.com/doc/current/cookbook/doctrine/file_uploads.html - it is very good solution. As for you question, where your script uploading file ??? you only get filename and writing it into database, but not uploading it Commented Jan 2, 2014 at 12:45
  • 1
    I know, I followed the documentation step by step, this is the reason I get no error Commented Jan 2, 2014 at 12:50
  • @Dmitriy.Net I'm Using Lifecycle Callbacks Commented Jan 2, 2014 at 12:51
  • Yes, but you must to upload file at your entity. See my answer Commented Jan 2, 2014 at 12:54

2 Answers 2

1

I find a solution, it's work, but I don't know if is the correctly way to do this. the solution : I modify just the function uploadAction

public function uploadAction(Request $request)
    {
        $document = new Document();
        $form = $this->createFormBuilder($document)
        ->add('file')
        ->getForm();

        if ($this->getRequest()->isMethod('POST')) {
        $form->bind($this->getRequest());
            $em = $this->getDoctrine()->getManager();

            $em->persist($document);
            $em->flush();

            return new Response("Ok");

    }

        return new Response("No");


    }
Sign up to request clarification or add additional context in comments.

Comments

0

You must uncoment upload line

namespace Upload\UploadBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

use Upload\UploadBundle\Entity\Document;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render('UploadBundle:Default:index.html.twig');
    }

    public function uploadAction(Request $request)
    {


        $em = $this->getDoctrine()->getManager();
        $document = new Document();
        $document->upload();

        $em->persist($document);
        $em->flush();
        return new Response("Ok");
    }
}

And at yours document entity add upload method

/**
 * @param $varfile
 *
 * @return $this
 */
public function setFile($file = null)
{
    $this->file = $file;

    return $this;
}

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

public function upload()
{
    // the file property can be empty if the field is not required
    if (null === $this->getFile()) {
        return;
    }

    // use the original file name here but you should
    // sanitize it at least to avoid any security issues

    // move takes the target directory and then the
    // target filename to move to
    $this->getFile()->move(
         $this->getUploadRootDir(),
         $this->getFile()->getClientOriginalName()
    );

    // set the path property to the filename where you've saved the file
    $this->file = $this->getFile()->getClientOriginalName();
            $this->chemain = $this->getFile()->getClientOriginalName();
}

/**
 * @return null|string
 */
public function getAbsolutePath()
{
    if($this->file)
    {

        return $this->getUploadRootDir().'/'.$this->file;
    }

    return null;
}

/**
 * @return null|string
 */
public function getWebPath()
{
    if($this->file)
    {
        return '/web/'.$this->getUploadDir().'/'.$this->file;
    }

    return null;
}

4 Comments

I do not have this function : getfile()
getfile is your getchemain()
Call to a member function move() on a non-object in Line : ` $this->getchemain()->move(`
stop ))) change getchemain to getfile and add function getfile()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.