如何在symfony 2中下载上传的文件?

时间:2012-07-25 13:27:03

标签: php symfony

我有一个文档实体,我希望网站的用户能够下载已上传的文件。 我不知道怎么做(我在DocumentController中尝试使用downloadAction但是我有一些错误)。

这是我的文档实体:

<?php
namespace MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * MyBundle\Entity\Document
 * @ORM\Table()
 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks
 */
class Document
{

    public function __toString() {
    return $this->document_type->getName();
    }


    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var date $endDate
     *
     * @ORM\Column(name="endDate", type="date")
     */
    private $endDate;

    /**
     * @ORM\ManyToOne(targetEntity="DocumentType")
     * @ORM\JoinColumn(name="document_type_id", referencedColumnName="id")
     */
    private $document_type;


    /**
     * @ORM\Column(type="string", length="255", nullable="TRUE")
     * @Assert\File(maxSize="6000000")
     */
    public $file;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    public $path;

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



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

    protected function getUploadRootDir()
    {
        // the absolute directory path where uploaded documents should be saved
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw when displaying uploaded doc/image in the view.
        return 'uploads/documents';
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->file) {
            // do whatever you want to generate a unique name
            $this->path = uniqid().'.'.$this->file->guessExtension();
        }
    }

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

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

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



    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }


    /**
     * Set endDate
     *
     * @param date $endDate
     */
    public function setEndDate($endDate)
    {
        $this->endDate = $endDate;
    }

    /**
     * Get endDate
     *
     * @return endDate 
     */
    public function getEndDate()
    {
        return $this->endDate;
    }

    /**
     * Set document_type
     *
     * @param Was\RHBundle\Entity\DocumentType $documentType
     */
    public function setDocumentType(MyBundle\Entity\DocumentType $documentType)
    {
        $this->document_type = $documentType;
    }

    /**
     * Get document_type
     *
     * @return MyBundle\Entity\DocumentType 
     */
    public function getDocumentType()
    {
        return $this->document_type;
    }



    /**
     * Set path
     *
     * @param string $path
     */
    public function setPath($path)
    {
        $this->path = $path;
    }

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

    /**
     * Set file
     *
     * @param string $file
     */
    public function setFile($file)
    {
        $this->file = $file;
    }

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

}

现在,这是我的DocumentController.php中的downloadAction:

public function downloadAction($id)
{   
    $em = $this->getDoctrine()->getEntityManager();

    $document = $em->getRepository('MyBundle:Document')->find($id);

    if (!$document) {
        throw $this->createNotFoundException('Unable to find the document');
    }   

        $headers = array(
            'Content-Type' => $document->getMimeType()
            'Content-Disposition' => 'attachment; filename="'.$document->getDocumentType().'"'
        );  

    $filename = $document->getUploadRootDir().'/'.$document->getDocumentType();

    return new Response(file_get_contents($filename), 200, $headers);
}

我有这个错误:

Call to undefined method MyBundle\Entity\Document::getMimeType()

3 个答案:

答案 0 :(得分:3)

我使用IgorwFileServeBundle

这是我在我的一个项目中使用的示例:

    $em   = $this->getDoctrine()->getEntityManager();
    $file = $em->getRepository('MyBundle:File')->find($id);

    $path = $file->getPath();
    $mimeType = $file->getMimeType();
    $folder = 'Public';
    $factory = $this->get('igorw_file_serve.response_factory');
    $response = $factory->create($folder.'/'.$path, $mimeType);        

    return $response;

我希望它可以提供帮助

答案 1 :(得分:0)

以下是我项目之一的代码

public function downloadAction()
{
    $items = $this->get('xxxx')->getXXX();
    $response = $this->render('xxx:xxx:xxx.csv.twig', array('items' => $items));

    $response->headers->set('Content-Type', 'text/csv');
    $response->headers->set('Content-Disposition', 'attachment; filename=budget.csv');

    return $response;
}

答案 2 :(得分:0)

将变量 $ mimeType 添加到文档实体

/**
 * @ORM\Column()
 * @Assert\NotBlank
 */
private $mimeType;

getters setters (或生成它们)

public function setMimeType($mimeType) {
    $this->mimeType = $mimeType;
    return $this;
}

public function getMimeType() {
    return $this->mimeType;
}

更新 数据库架构

php app/console doctrine:schema:update --force

并将 setMimeType 添加到 setFile 函数

/**
 * Set file
 *
 * @param string $file
 */
public function setFile($file)
{
    $this->file = $file;
    $this->setMimeType($this->getFile()->getMimeType());
}

然后您的控制器将正常工作。