我正在尝试将图像上传到我的 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 给出了错误的请求错误。