1

我实际上是在创建一个 api。我正在使用 vichuploaderBundler 导入文件并将它们放在特定目录中。由于我使用我的表单发送 POST 请求来创建资源,因此我的资源被创建,但文件不再保存。这是我当前的代码。

postController

/**
 * @Rest\View(statusCode=Response::HTTP_CREATED)
 * @Rest\Post("/posts")
 */
public function postPostsAction(Request $request)
{
    $post = new Post();
    $form = $this->createForm(PostType::class, $post);
    $form->submit($request->request->all()); // Validation des données

    if ($form->isValid()) {
        $post->setUpdatedAt(new \DateTime());
        $em = $this->get('doctrine.orm.entity_manager');
        $em->persist($post);
        $em->flush();
        return $post;
    } else {
        return $form;
    }
}

邮政类型

class PostType extends AbstractType
{
/**
 * {@inheritdoc}
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('title');
    $builder->add('description');
    $builder->add('imageName');
    $builder->add('imageFile', FileType::class);
}

/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Post',
        //An API must be stateless, Cross-Site Request Forgery must be disable
        'csrf_protection' => false,
    ));
}

/**
 * {@inheritdoc}
 */
public function getBlockPrefix()
{
    return 'appbundle_post';
}


}

帖子实体:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\VirtualProperty;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

 /**
 * Post
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
 * @ExclusionPolicy("all")
 * @Vich\Uploadable
 */
 class Post
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 * @Expose
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="Title", type="string", length=100)
 */
private $title;

/**
 * @var string
 * @Expose
 * @ORM\Column(name="Description", type="string", length=400, nullable=true)
 */
private $description;

/**
 * @var string
 * @Expose
 * @ORM\Column(name="imageName", type="string", length=255)
 */
private $imageName;

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

/**
 * NOTE: This is not a mapped field of entity metadata, just a simple property.
 *
 * @Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
 * @var File
 */
private $imageFile;

/**
 * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
 * of 'UploadedFile' is injected into this setter to trigger the  update. If this
 * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
 * must be able to accept an instance of 'File' as the bundle will inject one here
 * during Doctrine hydration.
 *
 * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
 * @Expose
 * @return Post
 */
public function setImageFile(File $image = null)
{
    $this->imageFile = $image;

    if ($image) {
        // 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();
    }

    return $this;
}

/**
 * @return File|null
 */
public function getImageFile()
{
    return $this->imageFile;
}

/**
 * Set imageName
 *
 * @param string $imageName
 *
 * @return Post
 */
public function setImageName($imageName)
{
    $this->imageName = $imageName;

    return $this;
}

/**
 * Get imageName
 *
 * @return string
 */
public function getImageName()
{
    return $this->imageName;
}

/**
 * Get id
 *
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * Set title
 *
 * @param string $title
 *
 * @return Post
 */
public function setTitle($title)
{
    $this->title = $title;

    return $this;
}

/**
 * Get title
 *
 * @return string
 */
public function getTitle()
{
    return $this->title;
}

/**
 * @return \DateTime
 */
public function getUpdatedAt()
{
    return $this->updatedAt;
}

/**
 * @param \DateTime $updatedAt
 */
public function setUpdatedAt($updatedAt)
{
    $this->updatedAt = $updatedAt;
}

/**
 * Set description
 *
 * @param string $description
 *
 * @return Post
 */
public function setDescription($description)
{
    $this->description = $description;

    return $this;
}

/**
 * Get description
 *
 * @return string
 */
public function getDescription()
{
    return $this->description;
}

}

编辑 :

这是我的 vichuploader 配置,在 config.yml

#vich uploader Configuration
vich_uploader:
db_driver: orm
mappings:
        product_image:
            uri_prefix:         /images/posts
            upload_destination: '%kernel.root_dir%/../web/images/posts'
            namer:              vich_uploader.namer_uniqid

            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true

在使用我的表格之前,我以这种方式上传:

 public function postPostsAction(Request $request)
 {
     $post = new Post();
     $post->setTitle($request->get('title'))
         ->setDescription($request->get('description'))
         ->setImageName($request->get('image_name'))
         ->setImageFile($request->files->get('imageFile'))
         // 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
         ->setUpdatedAt(new \DateTime());


     // On fait appel à doctrine pour seter un id lors de la création en base
     $em = $this->get('doctrine.orm.entity_manager');
     $em->persist($post);
     $em->flush();

     return $post;
 }

感谢您的帮助!

4

0 回答 0