使用我自己的表单在symfony2中上传文件

时间:2014-01-02 12:43:44

标签: php symfony file-upload symfony-forms

我正在尝试使用我自己的表格和symfony2上传文件。 我没有收到任何错误,并且文件的名称在数据库中正确添加,但文件未上传。

这是我的 routing.yml

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

树枝

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

我的控制器:

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

实体:

<?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;
    }
}

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您必须取消上传线

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

并在您的文档实体添加上传方法

/**
 * @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;
}

答案 1 :(得分:0)

我找到了一个解决方案,它的工作,但我不知道是否正确的方法来做到这一点。 解决方案:我只修改了函数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");


    }