上传图片时出错:调用成员函数guessExtension

时间:2014-11-07 00:30:43

标签: php symfony image-uploading

我有一个实体 Agence 相关的OneToOne与实体照片

的Agence

class Agence
{
   /**
    * @ORM\OneToOne(targetEntity="Project\DashboardBundle\Entity\Photo", cascade={"persist"})
    * @ORM\JoinColumn(nullable=true)
    */
 private $photo;

这是实体照片

的简介
<?php
namespace Project\DashboardBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;


/**
* Photo
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Project\DashboardBundle\Entity\PhotoRepository")
* @ORM\HasLifecycleCallbacks
*/
class Photo
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

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

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

/**
* @Assert\File(maxSize="1M")
*/
public $file;

  public function setFile($file)
{
$this->file = $file;

if (null !== $this->url) {
  $this->tempFilename = $this->url;

  $this->url = null;
  $this->alt = null;
 }
}

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


private $tempFilename;

/**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
public function preUpload()
{
 if (null === $this->file) {
  return;
}

$this->url = $this->file->guessExtension();

$this->alt = $this->file->getClientOriginalName();
}

/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
  if (null === $this->file) {
  return;
}

if (null !== $this->tempFilename) {
  $oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this->tempFilename;
  if (file_exists($oldFile)) {
    unlink($oldFile);
  }
}

$this->file->move(
  $this->getUploadRootDir(), 
  $this->id.'.'.$this->url  
 );
}

/**
* @ORM\PreRemove()
*/
public function preRemoveUpload()
{
  $this->tempFilename = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
}

/**
 * @ORM\PostRemove()
 */
public function removeUpload()
{
  if (file_exists($this->tempFilename)) {
  unlink($this->tempFilename);
}
}

public function getUploadDir()
{
  return 'uploads/img';
}

protected function getUploadRootDir()
{
  return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

public function getWebPath()
{
  return $this->getUploadDir().'/'.$this->getId().'.'.$this->getUrl();
}

尝试上传照片时出现此错误:

FatalErrorException:错误:在D:\ wamp \ www \ agence \ src \ Project \ DashboardBundle \ Entity \ Photo.php第135行中的非对象上调用成员函数guessExtension()

,奇怪的是,这个相同的代码在另一个实体上工作正常!!

解决  我忘了添加{{form_enctype(form)}}

1 个答案:

答案 0 :(得分:1)

你做得好 像那样插入你的表格 {{form_enctype(form)}}

action="{{ path('your_path') }}"  {{form_enctype(form)}}   method="post"