Php symfony 4.3,带vich捆绑包的api平台-如何上传多个文件

Php symfony 4.3,带vich捆绑包的api平台-如何上传多个文件,php,symfony,doctrine-orm,doctrine,api-platform.com,Php,Symfony,Doctrine Orm,Doctrine,Api Platform.com,我创建了一个带有一对多关系映像实体的demo1实体,并使用vich bundle包进行上传 人口遗传学 <?php namespace App\Entity; use ApiPlatform\Core\Annotation\ApiResource; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as

我创建了一个带有一对多关系映像实体的demo1实体,并使用vich bundle包进行上传

人口遗传学

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

use App\Controller\UploadImageAction;

/**
 * @ORM\Entity(repositoryClass="App\Repository\Demo1Repository")
 * @ApiResource(
 *     collectionOperations={
 *             "get",
 *              "post" ={
 *
 *                    "controller"=UploadImageAction::class,
 *                    "defaults"={"_api_receive"=false},
 *                    "denormalization_context"={"groups"={"image"}}
 *              }
 *     }
 * )
 */
class Demo1
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Image", mappedBy="myfiles")
     * @ORM\JoinColumn(nullable=false);
     */
    private $files;

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

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

    /**
     * @return Collection|Image[]
     */
    public function getFiles(): Collection
    {
        return $this->files;
    }

    public function addFile(Image $file): self
    {
        if (!$this->files->contains($file)) {
            $this->files[] = $file;
            $file->setMyfiles($this);
        }

        return $this;
    }

    public function removeFile(Image $file): self
    {
        if ($this->files->contains($file)) {
            $this->files->removeElement($file);
            // set the owning side to null (unless already changed)
            if ($file->getMyfiles() === $this) {
                $file->setMyfiles(null);
            }
        }

        return $this;
    }
}


请在下面找到一个将多个附件上载到邮件的示例

/应用程序/实体/附件

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use App\Controller\AttachmentMessageAction;

/**
 * @ApiResource(
 *   attributes={"pagination_enabled"=false},
 *      itemOperations={
 *          "get"={
 *              "access_control"="is_granted('ROLE_USER')",
 *              "normalization_context"={
 *                  "groups"={"get"}
 *              }
 *          }
 *      },
 *      collectionOperations={
 *          "get",
 *          "post"={
 *             "method"="POST",
 *             "path"="/attachments",
 *             "controller"=AttachmentMessageAction::class,
 *             "defaults"={"_api_receive"=false}
 *         }
 *      }
 * )
 * @ORM\Entity(repositoryClass="App\Repository\AttachmentRepository")
 * @Vich\Uploadable()
 */
class Attachment
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 * @Groups({"get"})
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Message", inversedBy="attachments")
 * @ORM\JoinColumn(nullable=true)
 * @Groups({"post", "get"})
 */
private $message;

/**
 * @Assert\File(
 *     maxSize = "2048k",
 *     maxSizeMessage = "File exceeds allowed size",
 *     mimeTypes = {"image/png","image/jpeg", "application/pdf", "application/x-pdf"},
 *     mimeTypesMessage = "Please upload a valid file"
 * )
 * @Assert\NotNull()
 * @Vich\UploadableField(mapping="message_attachment", fileNameProperty="filename")
 * @Groups({"post"})
 * @var File
 */
private $file;

/**
 * @ORM\Column(type="string", length=180)
 * @Groups({"post","get-owner"})
 * @var string
 */
private $filename;

/**
 * @ORM\Column(type="datetime")
 * @var \DateTime
 */
private $updatedAt;

/**
 * Constructor
 *
 * @param Message $message
 */
public function __construct(Message $message = null)
{
    $this->message = $message;
}

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


public function getMessage(): ?Message
{
    return $this->message;
}

public function setMessage(?Message $message): self
{
    $this->message = $message;

    return $this;
}

/**
 * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $attachment
 */
public function setFile(?File $file = null): void
{
    $this->file = $file;

    if (null !== $file) {
        // It is required that at least one field changes if you are using doctrine
        // otherwise the event listeners won't be called and the file is lost
        $this->updatedAt = new \DateTimeImmutable();
    }
}

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

public function getFilename(): ?string
{
    return $this->filename;
}

public function setFilename(?string $filename): void
{
    $this->filename = $filename;
}

public function getUpdatedAt(): ?\DateTimeInterface
{
    return $this->updatedAt;
}

public function setUpdatedAt(\DateTimeInterface $updatedAt): self
{
    $this->updatedAt = $updatedAt;

    return $this;
}

public function __toString()
{
    return $this->id . ':' . $this->filename;
}
}
和App/Controller/AttachmentMessageAction

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use ApiPlatform\Core\Validator\ValidatorInterface;
use ApiPlatform\Core\Validator\Exception\ValidationException;
use App\Entity\Attachment;
use App\Entity\Message;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\HttpFoundation\Request;

class AttachmentMessageAction extends AbstractController
{
/**
 * @var ValidatorInterface
 */
private $validator;
/**
 * @var EntityManagerInterface
 */
private $entityManager;

public function __construct(
    ValidatorInterface $validator,
    EntityManagerInterface $entityManager
)
{
    $this->validator = $validator;
    $this->entityManager = $entityManager;
}

public function __invoke(Request $request)
{ 
    $files = $request->files->get('file');
    $attachments = [];
    foreach ($files as $file) {
        $attachment = new Attachment();
        $attachment->setFile($file);
        $this->validator->validate($attachment);
        $this->entityManager->persist($attachment);

        $attachment->setFile(null);
        $attachments[] = $attachment;
    }
    $this->entityManager->flush();

    return $attachments;
}
}
编辑:应用程序/实体/消息的相关摘录(按要求):

 /**
 * @ORM\OneToMany(targetEntity="App\Entity\Attachment", mappedBy="message",cascade={"persist"}, orphanRemoval=true)
 * @Groups({"post", "get"})
 */
private $attachments;

....

public function __construct()
{
    $this->attachments = new ArrayCollection();
    $this->children = new ArrayCollection();
    $this->isDeletedBySender = false;
    $this->isDeletedByReceiver = false;
    $this->sentAt = new \DateTimeImmutable();
}

....

/**
 * @return Collection|Attachment[]
 */
public function getAttachments(): Collection
{
    return $this->attachments;
}

public function addAttachment(Attachment $attachment): self
{
    if (!$this->attachments->contains($attachment)) {
        $this->attachments[] = $attachment;
        $attachment->setMessage($this);
    }

    return $this;
}

public function removeAttachment(Attachment $attachment): self
{
    if ($this->attachments->contains($attachment)) {
        $this->attachments->removeElement($attachment);
        // set the owning side to null (unless already changed)
        if ($attachment->getMessage() === $this) {
            $attachment->setMessage(null);
        }
    }

    return $this;
}

请在下面查找将多个附件上载到邮件的示例

/应用程序/实体/附件

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use App\Controller\AttachmentMessageAction;

/**
 * @ApiResource(
 *   attributes={"pagination_enabled"=false},
 *      itemOperations={
 *          "get"={
 *              "access_control"="is_granted('ROLE_USER')",
 *              "normalization_context"={
 *                  "groups"={"get"}
 *              }
 *          }
 *      },
 *      collectionOperations={
 *          "get",
 *          "post"={
 *             "method"="POST",
 *             "path"="/attachments",
 *             "controller"=AttachmentMessageAction::class,
 *             "defaults"={"_api_receive"=false}
 *         }
 *      }
 * )
 * @ORM\Entity(repositoryClass="App\Repository\AttachmentRepository")
 * @Vich\Uploadable()
 */
class Attachment
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 * @Groups({"get"})
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Message", inversedBy="attachments")
 * @ORM\JoinColumn(nullable=true)
 * @Groups({"post", "get"})
 */
private $message;

/**
 * @Assert\File(
 *     maxSize = "2048k",
 *     maxSizeMessage = "File exceeds allowed size",
 *     mimeTypes = {"image/png","image/jpeg", "application/pdf", "application/x-pdf"},
 *     mimeTypesMessage = "Please upload a valid file"
 * )
 * @Assert\NotNull()
 * @Vich\UploadableField(mapping="message_attachment", fileNameProperty="filename")
 * @Groups({"post"})
 * @var File
 */
private $file;

/**
 * @ORM\Column(type="string", length=180)
 * @Groups({"post","get-owner"})
 * @var string
 */
private $filename;

/**
 * @ORM\Column(type="datetime")
 * @var \DateTime
 */
private $updatedAt;

/**
 * Constructor
 *
 * @param Message $message
 */
public function __construct(Message $message = null)
{
    $this->message = $message;
}

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


public function getMessage(): ?Message
{
    return $this->message;
}

public function setMessage(?Message $message): self
{
    $this->message = $message;

    return $this;
}

/**
 * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $attachment
 */
public function setFile(?File $file = null): void
{
    $this->file = $file;

    if (null !== $file) {
        // It is required that at least one field changes if you are using doctrine
        // otherwise the event listeners won't be called and the file is lost
        $this->updatedAt = new \DateTimeImmutable();
    }
}

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

public function getFilename(): ?string
{
    return $this->filename;
}

public function setFilename(?string $filename): void
{
    $this->filename = $filename;
}

public function getUpdatedAt(): ?\DateTimeInterface
{
    return $this->updatedAt;
}

public function setUpdatedAt(\DateTimeInterface $updatedAt): self
{
    $this->updatedAt = $updatedAt;

    return $this;
}

public function __toString()
{
    return $this->id . ':' . $this->filename;
}
}
和App/Controller/AttachmentMessageAction

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use ApiPlatform\Core\Validator\ValidatorInterface;
use ApiPlatform\Core\Validator\Exception\ValidationException;
use App\Entity\Attachment;
use App\Entity\Message;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\HttpFoundation\Request;

class AttachmentMessageAction extends AbstractController
{
/**
 * @var ValidatorInterface
 */
private $validator;
/**
 * @var EntityManagerInterface
 */
private $entityManager;

public function __construct(
    ValidatorInterface $validator,
    EntityManagerInterface $entityManager
)
{
    $this->validator = $validator;
    $this->entityManager = $entityManager;
}

public function __invoke(Request $request)
{ 
    $files = $request->files->get('file');
    $attachments = [];
    foreach ($files as $file) {
        $attachment = new Attachment();
        $attachment->setFile($file);
        $this->validator->validate($attachment);
        $this->entityManager->persist($attachment);

        $attachment->setFile(null);
        $attachments[] = $attachment;
    }
    $this->entityManager->flush();

    return $attachments;
}
}
编辑:应用程序/实体/消息的相关摘录(按要求):

 /**
 * @ORM\OneToMany(targetEntity="App\Entity\Attachment", mappedBy="message",cascade={"persist"}, orphanRemoval=true)
 * @Groups({"post", "get"})
 */
private $attachments;

....

public function __construct()
{
    $this->attachments = new ArrayCollection();
    $this->children = new ArrayCollection();
    $this->isDeletedBySender = false;
    $this->isDeletedByReceiver = false;
    $this->sentAt = new \DateTimeImmutable();
}

....

/**
 * @return Collection|Attachment[]
 */
public function getAttachments(): Collection
{
    return $this->attachments;
}

public function addAttachment(Attachment $attachment): self
{
    if (!$this->attachments->contains($attachment)) {
        $this->attachments[] = $attachment;
        $attachment->setMessage($this);
    }

    return $this;
}

public function removeAttachment(Attachment $attachment): self
{
    if ($this->attachments->contains($attachment)) {
        $this->attachments->removeElement($attachment);
        // set the owning side to null (unless already changed)
        if ($attachment->getMessage() === $this) {
            $attachment->setMessage(null);
        }
    }

    return $this;
}

请提供信息实体以及我编辑了我的回答要求。请检查它。我尝试了您的示例,但它对我无效,我得到:“未能将类\“App\\Entity\\Contact\”的属性\“attachments\”值反规范化:属性路径\“attachments\”中给定的\“App\\Entity\\Attachment\”类型的预期参数\“App\\Entity\\Image\”,请提供信息实体以及我编辑了我的回答要求。请检查它。我尝试了您的示例,但它对我无效,我得到:“未能将类\“App\\Entity\\Contact\”的属性\“attachments\”值反规范化:属性路径\“attachments\”中给定的\“App\\Entity\\Attachment\”类型的预期参数\“App\\Entity\\Image\”,