Symfony的 - API平台 - 文件上传

问题描述 投票:0回答:1

我试图实现与API PLatform使用VICH的Documentation以下文件上传。但它不工作,准确地说,媒体目标不是由我对我的要求发送文件的水分。

我跟着相当准确的API平台提供的食谱,但它似乎并不认为我的形式处理该请求很好,因为它没有通过约束验证,我了解从API这样的回答:

{
    "type": "https:\/\/tools.ietf.org\/html\/rfc2616#section-10",
    "title": "An error occurred",
    "detail": "file: This value should not be null.",
    "violations": [
        {
        "propertyPath": "file",
        "message": "This value should not be null."
        }
    ]
}

我的要求是基本:标题是多部分/格式数据和I发送单个和小文件(78Ko):“文件” => image.jpg的

当我倾倒我的$ request对象,该文件是在里面,但是$形式 - >的getData()未水。任何想法,为什么?

这里是我的媒体目标:

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Traits\updatedAt;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Entity\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @ApiResource(iri="http://schema.org/MediaObject", collectionOperations={
 *     "get",
 *     "post"={
 *         "method"="POST",
 *         "path"="/media_objects",
 *         "controller"=CreateMediaObjectAction::class,
 *         "defaults"={"_api_receive"=false},
 *     },
 * })
 * @Vich\Uploadable
 * @ORM\Entity(repositoryClass="App\Repository\MediaObjectRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class MediaObject
{
    use updatedAt;

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var File|null
     * @Assert\NotNull()
     * @Vich\UploadableField(mapping="media_object", fileNameProperty="contentUrl")
     */
    public $file;

    /**
     * @var string|null
     * @ORM\Column(type="string", length=255, nullable=true)
     * @ApiProperty(iri="http://schema.org/contentUrl")
     */
    private $contentUrl;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getFile(): ?string
    {
        return $this->file;
    }

    /**
     * @param string $file
     *
     * @return MediaObject
     * @throws \Exception
     */
    public function setFile(string $file): self
    {
        $this->file = $file;

        if (null !== $file) {
            $this->updatedAt = new DateTimeImmutable();
        }

        return $this;
    }

    public function getContentUrl(): ?string
    {
        return $this->contentUrl;
    }

    public function setContentUrl(?string $contentUrl): self
    {
        $this->contentUrl = $contentUrl;

        return $this;
    }

}

这里是我的媒体对象类型:

namespace App\Form;

use App\Entity\MediaObject;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichFileType;

class MediaObjectType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // Configure each fields you want to be submitted here, like a classic form.
            ->add('file', VichFileType::class, [
                'label' => 'label.file',
                'required' => false,
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => MediaObject::class,
            'csrf_protection' => false,
        ]);
    }

    public function getBlockPrefix()
    {
        return '';
    }
}

这里是我的控制器:

namespace App\Controller;

use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException;
use App\Entity\MediaObject;
use App\Form\MediaObjectType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Validator\ValidatorInterface;

final class CreateMediaObjectController extends AbstractController
{
    private $validator;
    private $doctrine;
    private $factory;

    public function __construct(RegistryInterface $doctrine, FormFactoryInterface $factory, ValidatorInterface $validator)
    {
        $this->validator = $validator;
        $this->doctrine  = $doctrine;
        $this->factory   = $factory;
    }

    /**
     * @param Request $request
     * @Route("media_objects", name="media")
     *
     * @return MediaObject
     */
    public function mediaCreation(Request $request): MediaObject
    {
        $mediaObject = new MediaObject();

        $form = $this->factory->create(MediaObjectType::class, $mediaObject);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            $em = $this->doctrine->getManager();
            $em->persist($mediaObject);
            $em->flush();

            // Prevent the serialization of the file property
            $mediaObject->file = null;

            return $mediaObject;
        }

        // This will be handled by API Platform and returns a validation error.
        throw new ValidationException($this->validator->validate($mediaObject));
    }
}
symfony file-upload api-platform.com vichuploaderbundle
1个回答
0
投票

我使用的邮递员,symfony的4.x的这个答案。

  1. API URL:本地主机/火/ media_objects(本地主机=>基本URL)
  2. 选择表单数据=>重点应该是文件,然后选择文件类型(如果你悬停右侧输入你会看到下拉)
  3. 选择文件和文章。

注意:您必须拥有相似配置的config /包/ vich_uploader.yaml

vich_uploader:db_driver:蠕虫

mappings:
    media_object:
        uri_prefix: /media
        upload_destination: '%kernel.project_dir%/public/media'
        namer: Vich\UploaderBundle\Naming\UniqidNamer
© www.soinside.com 2019 - 2024. All rights reserved.