2012-11-16 2 views
2

내 Restful API에서 한 번의 호출로 파일을 업로드하고 싶습니다. 테스트에서 폼이 동시에 초기화되고 바인딩되지만 모든 데이터 필드 폼은 비어 있으며 결과는 내 데이터베이스에 빈 레코드입니다.Symfony2를 사용하여 하나의 webservice 호출에서 파일을 업로드하는 방법은 무엇입니까?

양식보기로 전달한 다음 제출하면 모두 괜찮지 만 한 번의 호출로 Webservice를 호출하려고합니다. 웹 서비스는 백본 앱에 의해 소비되도록 목적지 지정됩니다.

도움 주셔서 감사합니다.

내 시험 :

public function uploadAction(Request $request, $directory, $_format) 
{ 
    $document = new Media(); 
    $document->setDirectory($directory); 
    $form = $this->createFormBuilder($document, array('csrf_protection' => false)) 
     /*->add('directory', 'hidden', array(
      'data' => $directory 
     ))*/ 
     ->add('file') 
     ->getForm() 
    ; 
    if ($this->getRequest()->isMethod('POST')) { 

     $form->bind($request); 
     if ($form->isValid()) { 
      $em = $this->getDoctrine()->getManager(); 
      $em->persist($document); 
      $em->flush(); 
      if($document->getId() !== '') 
       return $this->redirect($this->generateUrl('media_show', array('id'=>$document->getId(), 'format'=>$_format))); 
     }else{ 
      $response = new Response(serialize($form->getErrors()), 406); 
      return $response; 
     } 
    } 

    return array('form' => $form->createView()); 
} 

내 미디어 엔티티 : 내 컨트롤러 액션이

$client = static::createClient(); 
$photo = new UploadedFile(
     '/Userdirectory/test.jpg', 
     'photo.jpg', 
     'image/jpeg', 
     14415 
); 
$crawler = $client->request('POST', '/ws/upload/mydirectory', array(), array('form[file]' => $photo), array('Content-Type'=>'multipart/formdata')); 

있습니다

<?php 

    namespace MyRestBundle\RestBundle\Entity; 
    use Symfony\Component\Serializer\Normalizer\NormalizableInterface; 
    use Symfony\Component\Serializer\Normalizer\NormalizerInterface; 
    use Doctrine\ORM\Mapping as ORM; 
    use Symfony\Component\Validator\Constraints as Assert; 
    use Symfony\Component\HttpFoundation\File\UploadedFile; 
    use Symfony\Component\HttpFoundation\Request; 
    /** 
    * @ORM\Entity 
    * @ORM\HasLifecycleCallbacks 
    */ 
    class Media 
    { 
     /** 
     * @ORM\Id 
     * @ORM\Column(type="integer") 
     * @ORM\GeneratedValue(strategy="AUTO") 
     */ 
     protected $id; 

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

     public $directory; 

     /** 
     * @Assert\File(maxSize="6000000") 
     */ 
     public $file; 

     /** 
     * @see \Symfony\Component\Serializer\Normalizer\NormalizableInterface 
     */ 
     function normalize(NormalizerInterface $normalizer, $format= null) 
     { 
      return array(
       'path' => $this->getPath() 
      ); 
     } 

     /** 
     * @see 
     */ 
     function denormalize(NormalizerInterface $normalizer, $data, $format = null) 
     { 
      if (isset($data['path'])) 
      { 
       $this->setPath($data['path']); 
      } 
     } 

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

     protected 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/'.(null === $this->directory ? 'documents' : $this->directory); 
     } 

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

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

      // if there is an error when moving the file, an exception will 
      // be automatically thrown by move(). This will properly prevent 
      // the entity from being persisted to the database on error 
      $this->file->move($this->getUploadRootDir(), $this->path); 

      unset($this->file); 
     } 

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

     /** 
     * Set Directory 
     * 
     * @param string $directory 
     * @return Media 
     */ 
     public function setDirectory($directory) 
     { 
      $this->directory = $directory; 

      return $this; 
     } 

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

      return $this; 
     } 

     /** 
     * Get path 
     * 
     * @return string 
     */ 
     public function getPath() 
     { 
      $request = Request::createFromGlobals(); 
      return $request->getHost().'/'.$this->path; 
     } 

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

내 라우팅 :

upload_dir_media: 
    pattern:  /upload/{directory}.{_format} 
    defaults:  { _controller: MyRestBundle:Media:upload, _format: html } 
    requirements: { _method: POST } 
+0

은 ($ document-> getId()! == '') 에 중괄호가 있어야합니다. – Gigala

답변

0

이 문제를 간단한 상태로 나눠보십시오. 하나의 게시물로 '텍스트'또는 변수를 웹 서비스에 게시하는 방법은 무엇입니까? 이미지는 긴 문자열 일뿐입니다. PHP 함수 imagecreatefromstring 또는 imgtostring을 확인하십시오. 이것은 종종 당신의 장면 뒤에서 일어나는 일입니다. 일단 간단한 문제를 풀면 원래의 문제를 풀 수 있다는 것을 증명할 수 있습니다.