簡體   English   中英

如何使用Symfony2在一個Web服務調用中上傳文件?

[英]How to upload a file in one webservice call with Symfony2?

在我的Restful API中,我想在一個調用中上傳文件。 在我的測試中,表單是同時初始化和綁定的,但是我所有的數據字段表單都是空的,結果是數據庫中的記錄為空。

如果我通過表單視圖然后提交,那么一切都很好,但是我想一次調用Web服務。 該Web服務注定要由主干應用程序使用。

謝謝你的幫助。

我的測試:

$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'));

有我的控制器動作:

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());
}

我的媒體實體:

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

嘗試將此問題分解為簡單狀態。 您如何通過一篇文章將“文本”或變量發布到Web服務? 因為圖像只是一個長字符串。 查看php函數imagecreatefromstringimgtostring 這通常是圖像傳輸協議的幕后故事。解決了較簡單的問題之后,您將證明可以解決原始問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM