我正按照Symfony Using the id as the filename文档中的说明尝试将文件上传到我的应用程序。但是,如果有以前上传的文件,则不会发生任何事情。
我的表单只包含一个字段File
,与Basic Setup中描述的实体Document
相关联,唯一的区别是没有定义$name
属性
我的实体定义:
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Document
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
/**
* @Assert\File()
*/
private $file;
}
我的表单定义(在奏鸣曲管理类中):
/**
* @param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('file');
}
当文档是新的时,文件会正确上传。 但是如果我尝试上传其他文件来替换以前的文件,那么它什么都不做,旧文件仍然存在存在。
关键区域(Using the id as the filename):
use Symfony\Component\HttpFoundation\File\UploadedFile;
// ...
class Document
{
// ...
/**
* Sets file.
*
* @param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
// check if we have an old image path
if (is_file($this->getAbsolutePath())) {
// store the old name to delete after the update
$this->temp = $this->getAbsolutePath();
} else {
$this->path = 'initial';
}
}
// ...
}
第二次,当我尝试更改以前上传的文件时,这些方法不会被执行(Using the id as the filename):
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Document
{
// ...
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->getFile()) {
$this->path = $this->getFile()->guessExtension();
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->getFile()) {
return;
}
// check if we have an old image
if (isset($this->temp)) {
// delete the old image
unlink($this->temp);
// clear the temp image path
$this->temp = null;
}
// you must throw an exception here if the file cannot be moved
// so that the entity is not persisted to the database
// which the UploadedFile move() method does
$this->getFile()->move(
$this->getUploadRootDir(),
$this->id.'.'.$this->getFile()->guessExtension()
);
$this->setFile(null);
}
}
任何人都可以告诉我,我可能做错了吗?
答案 0 :(得分:1)
描述的错误(“但是当有先前上传的文件时没有任何反应。”)表明这是一个目录权限问题,可以防止覆盖现有文件。
无论如何,您提到的文章最近被宣布为过时的,并被另一篇文章取代:How to Upload Files。也许阅读这篇新文章可以帮助您发现问题。