2

私の Restful API では、1 回の呼び出しでファイルをアップロードしたいと考えています。私のテストでは、フォームは同時に初期化されバインドされますが、すべてのデータ フィールド フォームは空であり、結果はデー​​タベース内の空のレコードになります。

フォームビューを渡して送信すると、すべて問題ありませんが、1回の呼び出しで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 }
4

1 に答える 1

0

この問題を単純な状態に分解してみてください。1 回の投稿で「テキスト」または変数を Web サービスにどのように投稿しますか? 画像はただの長い文字列だからです。PHP関数imagecreatefromstringまたはimgtostringを確認してください。これは、多くの場合、画像転送プロトコルの舞台裏で行われていることです。より単純な問題を解決すると、元の問題を解決できることが証明されます。

于 2012-12-07T01:38:31.070 に答える