2014-09-12 2 views
1

Symfony2에서 여러 파일을 업로드하려고합니다. 나는 컨트롤러에서 처리하지 않고이 작업을 수행해야하고, 그 trought 라이프 사이클을 시도,하지만 난, 난 방법, 내가 수정할 필요가 있다고 생각 내 개체의 여러 인스턴스를 생성하지 못할 :Symfony2에 여러 파일 업로드

:

/** 
* Sets file. 
* 
* @param UploadedFile $photo 
*/ 
public function setPhoto(UploadedFile $photo = null) 
{ 

    $this->photo = $photo; 
    if (isset($this->path)) { 
     $this->temp = $this->path; 
     $this->path = null; 
    } else { 
     $this->path = 'initial'; 
    } 
} 

그런 일에

/** 
* Sets file. 
* 
* @param ArrayCollection $photo 
*/ 
public function setPhoto(ArrayCollection $photo = null) 
{ 
    foreach ($photo as $photos) { 
     $file = new UploadedFile(); 
     $this->photo = $file; 
    } 

} 

초보자를 부탁드립니다.

답변

0

Symfony2를 사용하면 여러 파일 업로드가 까다로울 수 있습니다. 나는이 여러 파일을 업로드 할 교리와 함께 PHP 업로드를 사용

if(isset($_FILES['files'])) 
    { 
     $errors= array(); 
     foreach($_FILES['files']['tmp_name'] as $key => $tmp_name) 
     { 
      $file_name = $_FILES['files']['name'][$key]; 
      $file_size =$_FILES['files']['size'][$key]; 
      $file_tmp =$_FILES['files']['tmp_name'][$key]; 
      $file_type=$_FILES['files']['type'][$key]; 
      if($file_size > 6097152) //whatever size you want 
      { 
       $errors[]='File size must be less than 6 MB'; 
      } 
      $entity = new Entity; //your file entity 

      //Do whatever you want with the entity... 

      $request = $this->get('request'); 
      $em = $this->getDoctrine()->getManager(); 
      $em->persist($entity); 
      $em->flush(); 
      $desired_dir=__DIR__.'/../../../../web/[Your desired folder]/'.$entity->getId()."/"; 
      if(empty($errors)==true) 
      { 
       if(is_dir($desired_dir)==false) 
       { 
        mkdir("$desired_dir", 0700);  // Create directory if it does not exist 
       } 
       if(is_dir("$desired_dir/".$file_name)==false) 
       { 
        move_uploaded_file($file_tmp,__DIR__.'/../../../../web/[Your desired folder]/'.$entity->getId()."/".$file_name); 
       } 
       else 
       {         //rename the file if another one exist 
        $new_dir=__DIR__.'/../../../../web/Flightpics/'.$flight->getId()."/".$file_name.time(); 
        rename($file_tmp,$new_dir) ; 
       } 
      } 
      else 
      { 
       //print errors if needed 
      } 
     } 
     if(empty($error)){ 
       //print success if needed 
     } 
    } 

모든 파일은 웹/[폴더]/[엔터티 ID] 폴더로 처리됩니다. HTML 코드에서 양식은 다음과 같아야합니다.

<form action="" method="POST" enctype="multipart/form-data"> 
        <input type="file" name="files[]" multiple/ required> 
        <hr> 
        <input type="submit"/ value="Ajouter" class="btn btn-success"> 
        </form> 

파일 배열을 얻으려면 name = "files []"부분을 잊지 마십시오.