2016-08-24 30 views
-2

我嘗試使用Symfony2 bundle VichUploaderBundle。當我使用保存在數據庫中的記錄並請求Product->getPicture()時,我收到上傳的文件信息。但是當我嘗試創建它時Symfony2如何上傳文件Product-> getPicture()在新記錄上返回null

$product = new Product(); 
$product->getPicture() 

我得到空對象並且無法上載文件。 我的產品分類。

/** 
* @ORM\Entity(repositoryClass="CreLabs\Bundle\ProductBundle\Entity\ProductRepository") 
* @ORM\Table(name="product") 
*/ 
class Product { 

    use ORMBehaviors\Translatable\Translatable; 

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

    /** 
    * @ORM\Column(type="string", length=20, nullable=true) 
    */ 
    protected $sku; 

    /** 
    * @ORM\Column(type="float", scale=2) 
    */ 
    protected $price; 

    /** 
    * @ORM\Column(type="float", scale=2, nullable=true) 
    */ 
    protected $msrp_price; 

    /** 
    * @ORM\Column(type="string", nullable=true) 
    * @Assert\File(mimeTypes={ "image/jpeg" }) 
    */ 
    protected $picture; 

    /** 
    * @ManyToOne(targetEntity="\CreLabs\Bundle\SettingBundle\Entity\Category", inversedBy="products") 
    * @JoinColumn(name="category_id", referencedColumnName="id", onDelete="cascade") 
    * @Assert\NotNull() 
    */ 
    protected $category; 

    /** 
    * @ManyToOne(targetEntity="\CreLabs\Bundle\SettingBundle\Entity\Manufacturer", inversedBy="products") 
    * @JoinColumn(name="manufacturer_id", referencedColumnName="id", onDelete="cascade") 
    * @Assert\NotNull() 
    */ 
    protected $manufacturer; 

    /** 
    * @ORM\Column(type="datetime", nullable=false) 
    */ 
    protected $created_at; 

    /** 
    * @ORM\Column(type="datetime", nullable=true) 
    */ 
    protected $updated_at; 

如何我嘗試在新的記錄

$entityManager = $this->getEntityManager(); 
$product = new Product(); 

     $file = $product->getPicture(); 
     $fileName = md5(uniqid()).'.'.$file->guessExtension(); 
     $file->move(
      $productDirectory, 
      $fileName 
     ); 
$product->setPicture($fileName); 

異常使用上guessExtension

任何想法?

+0

爲什麼你會想到它是任何比'null'新'Product'例如否則如果'picture'屬性是當尚未設置任何內容?而你的意思是*你不能上傳,因爲這*。你的圖片屬性是順便說一下的。不是對象。 –

+0

只需按照VichUploaderBundle網站上的*使用*指南中的說明進行操作https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/usage.md –

+0

是,尚未設置新產品圖片屬性。上傳只適用於更新記錄,但不適用於創建新記錄 – Staff

回答

0

發現問題

$imageFile = $request->files->get('form')['imageFile']['file']; 
$product->setImageFile($imageFile); 

現在,文件上傳和創造新的紀錄

+0

更新時,我收到另一個問題「無法找到文件。」 並解決:)非常感謝你:) – Staff