2013-04-22 5 views
6

Symfony2를 사용하여 파일을 업로드 한 이후로 모든 것이 바뀌 었습니다. How to handle File Uploads with Doctrine의 가이드를 따르지만 오래되어 작동하지 않습니다.Symfony 2.2 업로드 파일

내가 양식을 결합하려고 할 때 오류를 얻을 수

Catchable Fatal Error: Argument 1 passed to Entity\Portada::setFile() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, string given, ... 

이 내 컨트롤러

/** 
* @Route("/upload", name="documento_upload") 
* @Method("POST") 
* @Template() 
*/ 
public function uploadAction(Request $request) 
{ 
    $portada = new Portada(); 
    $form = $this->buildUploadForm($portada); 
    $form->bind($request); 

    if ($form->isValid()) { 
     $portada->upload(); 
    } else { 
     throw new \Exception("Hay un error en el formulario"); 

    } 

    //... 
} 

내 실체

<?php 

namespace MyName\MyBundle\Entity; 

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

class Portada 
{ 
    /** 
    * @Assert\File(maxSize="6000000") 
    */ 
    private $file; 

    public $path; 

    /** 
    * Sets file. 
    * 
    * @param UploadedFile $file 
    */ 
    public function setFile(UploadedFile $file = null) 
    { 
     $this->file = $file; 
    } 

    public function upload() 
    { 
     $this->path = $this->getFile()->getClientOriginalName(); 

     $this->getFile()->move(
      $this->getUploadRootDir(), 
      $this->path 
     ); 

     $this->file = null; 
    } 

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

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

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

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

    protected function getUploadDir() 
    { 
     return 'uploads/portada'; 
    } 
} 

답변

15

난 후 내 양식에 PHP 버전을 추가 잊지 완벽하게 추가 된 작업

<form action="{{ path('documento_upload') }}" method="post" {{ form_enctype(upload_form) }}> 
    {{ form_widget(upload_form) }} 
    <button type="submit" class="btn btn-primary">Upload</button> 
</form> 
+0

+1 aaaaahhhhh .... thanks : –

+0

폼 빌더없이이 작업을 수행 할 수 있습니까? – Gigala

+2

@Gigala 가능하지만 시도하지 않습니다. FileBag를 반환하는'$ this-> getRequest() -> files'를 체크하면 쓸데없는 사용 양식을 옮길 방법을 확인할 수 있습니다. – rkmax

관련 문제