1

我正在尝试将图像上传到我的 Symfony2 Rest 服务器。我使用 VichUploaderBundle 来处理这个问题。我按照此处发布的说明进行操作。

所以我基本上将以下内容添加到我的 Post.php (我想附加图像的实体)

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

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

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





/**
 * 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
 */
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 \DateTime('now');
    }
}

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

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

将以下内容添加到我的 config.yml

vich_uploader:
    db_driver: orm
    mappings:
        product_image:
            uri_prefix:         /images/products
            upload_destination: %kernel.root_dir%/../web/images/products

将此行添加到 PostType.php

->add('imagefile', 'file')

我现在正在尝试测试此功能是否有效。由于这是一个 Rest API,我正在使用 Postman(Chrome 扩展)来尝试发布新帖子。这是我要与收到的错误一起发送的内容

在此处输入图像描述

PS:我故意省略了标头字段,因为 Content-Type application/json 给出了错误的请求错误。

4

1 回答 1

1

工作形式

问题出在服务器端。我不应该将其添加 ->add('imagefile', 'file')到 PostType.php,而是将其添加到控制器中 $form = $this->createForm(new PostType(), $entity, array("method" => $request->getMethod ()))->add('imageFile','file');

于 2015-07-07T14:09:53.987 回答