Question

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 ?

Was it helpful?

Solution

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");


    }

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top