无法将上传的文件存储到Sonata Media Symfony 4.2中

时间:2019-01-27 06:57:17

标签: symfony4 sonata-media-bundle

我正在从表单上载多个媒体文件,并试图将它们保存到奏鸣曲媒体中。我的文件正在上传,但是很遗憾,我无法保存媒体并收到此错误。

  

找不到服务“ sonata.media.pool”:即使它存在于应用程序的容器中,“ App \ Controller \ PagesController”内部的容器也是一个较小的服务定位器,仅了解“教义”,“表单”。 factory”,“ http_kernel”,“ parameter_bag”,“ request_stack”,“ router”,“ security.authorization_checker”,“ security.csrf.token_manager”,“ security.token_storage”,“ serializer”,“ session”,“ tempulation”和“树枝”服务。尝试改用依赖项注入。

这是我的控制人

>>> from itertools import repeat
>>> list(zip_longest(*repeat(map(float, string.replace(',', '').split()),
                             times=2),
                     fillvalue=float('inf')))
[(144.963286, -37.814212), (42.0, inf)]

这是我的实体

    public function customerToken(Request $request)
{
    $CustomerToken = new CustomerToken();
    $form = $this->createForm(CustomerTokenFormType::class, $CustomerToken);
    $form->handleRequest($request);
    if ($request->isXmlHttpRequest()) {
        if ($form->isSubmitted() && $request->getMethod() == 'POST') {

           $files= $form->get('attachments')->getData();
           if(!empty($files)){
               foreach ($files as $file ){
                   $filename = md5(uniqid()) . '.' .$file->guessExtension();
                   $filePath = $_SERVER['DOCUMENT_ROOT'] . '/tmp/';
                   $path = sha1(uniqid(mt_rand(), true)) . '.' . $file->guessExtension();
                   $file->move($filePath, $filename);
                   $newfilePath = $filePath.$filename;//'http://127.0.0.1:8000/tmp/ec2a2874414744ae9596258199eecd59.jpeg'
                   $myfile = new UploadedFile($newfilePath, $filename);
                   $filemedia = $this->uploadMediaAction($myfile);
                   $CustomerToken->addMedium($filemedia['media']);
                   //unlink($filePath);//once file uploaded in media then remo
                   ///$CustomerToken->addMedium($file);
               }
           }
            // $form->getData() holds the submitted values
            // but, the original `$task` variable has also been updated
            $data = $form->getData();
            // ... perform some action, such as saving the task to the database
            // for example, if Task is a Doctrine entity, save it!
            $entityManager = $this->getDoctrine()->getManager();
            $data->setCreatedAt(new \DateTime('now'));
            $data->setUpdatedAt(new \DateTime('now'));
            $entityManager->persist($CustomerToken);
            $entityManager->flush();
            $success = true;
            return new JsonResponse(array('status' => $success));
        }
    }
    return $this->render('pages/your-token.html.twig', [
        'controller_name' => 'PagesController',
        'form' => $form->createView(),
    ]);
}

public function uploadMediaAction($file)
    {
        $MediaErrors = array();
        $MediaErrors['error'] = false;

        if (!$file instanceof UploadedFile) {
            $MediaErrors['message'] = ['Missing file.'];
            $MediaErrors['error'] = true;
        } else {
            $AllowedMimetypesImagesAndFile = array(
                'image/jpeg',
                'image/png',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'application/msword',
                'application/pdf',
                'application/x-pdf'
            );
            if (!in_array($file->getMimeType(), $AllowedMimetypesImagesAndFile)) {
                $MediaErrors['message'] = ['Invalid file/image.'];
                $MediaErrors['error'] = true;
            }
            if (!$MediaErrors['error']) {
                $mediaManager = $this->container->get('sonata.media.pool');
                $media = new Media();
                $media->setBinaryContent($file);
                $media->setContext('default');

                $media_sizes = getimagesize($file);
                $media->setWidth($media_sizes[0]);
                $media->setHeight($media_sizes[1]);



                $ImagemimeTypes = array('image/jpeg', 'image/png');
                $FilemimeTypes = array(
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    'application/msword',
                    'application/pdf',
                    'application/x-pdf'
                );
                if (in_array($file->getMimeType(), $FilemimeTypes)) {
                    $media->setProviderName('sonata.media.provider.file');
                }
                if (in_array($file->getMimeType(), $ImagemimeTypes)) {
                    $media->setProviderName('sonata.media.provider.image');
                }
                $media->setEnabled(true);
                $mediaManager->save($media);
                $MediaErrors['media'] = $media;
            }
        }

        return $MediaErrors;
    }

Services.yaml

            namespace App\Entity;

        use App\Application\Sonata\MediaBundle\Entity\Media;
        use Doctrine\Common\Collections\ArrayCollection;
        use Doctrine\Common\Collections\Collection;
        use Doctrine\ORM\Mapping as ORM;
        use Symfony\Component\Validator\Constraints as Assert;

        /**
         * @ORM\Table(name="cms_customer_token")
         * @ORM\Entity(repositoryClass="App\Repository\BaseRepository")
         */
        class CustomerToken extends Base
        {


            /**
             * @Assert\Regex(pattern="/^.*\.(jpg|jpeg|gif|JPG|png|PNG|pdf|PDF|doc|docx)$/", message="Not valid file, please select valid file format (PDF,PNG,JPG).")
             * @ORM\ManyToMany(targetEntity="App\Application\Sonata\MediaBundle\Entity\Media")
             * @ORM\JoinTable(name="cms_token_attachemnts",
             *      joinColumns={@ORM\JoinColumn(name="token_id", referencedColumnName="id")},
             *      inverseJoinColumns={@ORM\JoinColumn(name="media_id", referencedColumnName="id")}
             *      )
             */
            protected $media;

            public function __construct()
            {
                $this->media = new ArrayCollection();
            }

            /**
             * @return Collection|Media[]
             */
            public function getMedia(): Collection
            {
                return $this->media;
            }

            public function addMedium(Media $medium): self
            {
                if (!$this->media->contains($medium)) {
                    $this->media[] = $medium;
                }

                return $this;
            }

            public function removeMedium(Media $medium): self
            {
                if ($this->media->contains($medium)) {
                    $this->media->removeElement($medium);
                }

                return $this;
            }

        }

0 个答案:

没有答案