2013-04-22 42 views
6

Đã một lúc kể từ khi tôi tải lên các tệp với Symfony2 và có vẻ như mọi thứ đã thay đổi, hãy làm theo hướng dẫn trong How to handle File Uploads with Doctrine nhưng đã lỗi thời và không hoạt động.Symfony 2.2 tải lên tập tin

khi tôi cố gắng để ràng buộc dưới hình thức một nhận được một lỗi

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

đây là bộ điều khiển của tôi

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

    } 

    //... 
} 

thực thể của tôi

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

Trả lời

15

tôi quên thêm enctype mẫu của tôi sau khi đã thêm công việc hoàn hảo

<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 .... cảm ơn :) –

+0

có thể thực hiện việc này mà không cần trình tạo biểu mẫu không? – Gigala

+2

@Gigala có thể nhưng tôi không thử. kiểm tra '$ this-> getRequest() -> files' trả về một FileBag và bạn có thể kiểm tra cách di chuyển hình thức sử dụng withut – rkmax

Các vấn đề liên quan