【发布时间】:2015-02-27 17:36:37
【问题描述】:
我在 2.6 上遇到文件上传问题,在以前的版本上运行良好。我不知道问题是什么,没有错误,当我转储帖子对象时,我在那里看到一个文件名,但图像文件夹中没有文件。
我的图片文件夹在 myproject/web/images 中。
使用 SonataAdmin 上传文件,同样没有错误。
谁能指出我做错了什么或发生了什么变化?
编辑:仔细阅读文件夹后,我注意到它在 /var/www/html 中创建了另一个 web/images 文件夹。
知道如何正确吗?我的项目文件夹在 /var/www/html/myproject 中。
尝试再添加 2 个 /../../ 但出现错误:Unable to create the "/var/www/html/myproject/src/AppBundle/Entity/../../../../../../web/images/" directory。并删除了 2 /../../ 仍然没有。
使用以下命令在 twig 中调用文件:
{% for photo in photos %}
<a href="{{ asset(['images/', photo.image]|join) }}">
<img src="{{ asset(['images/', photo.image]|join) }}" width="400" height="600" alt=""/>
</a>
{% endfor %}
发布实体
/**
* @var string
*
* @ORM\Column(name="file", type="string", length=255)
*/
private $image;
public $file;
/**
* Set image
*
* @param string $image
* @return Post
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* @return string
*/
public function getImage()
{
return $this->image;
}
public function getUploadDir()
{
return 'images/';
}
public function getUploadRootDir()
{
return __DIR__ . '/../../../../web/' . $this->getUploadDir();
}
public function getWebPath()
{
return null === $this->image ? null : $this->getUploadDir() . '/' . $this->image;
}
public function getAbsolutePath()
{
return null === $this->image ? null : $this->getUploadRootDir() . '/' . $this->image;
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->file) {
$this->image = uniqid() . '.' . $this->file->guessExtension();
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
// If there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->file->move($this->getUploadRootDir(), $this->image);
$this->file = null;
}
/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
【问题讨论】:
-
myproject/web/images 是可写的吗?你给了它什么权限?
-
是的。将所有者更改为 www-data:www-data,权限为 775。
-
你能试试这个,让我们知道它是否工作 public function getUploadDir() { return 'images'; //删除尾部斜杠(/) }
-
是的,先生,我也试过了,还是不行。
-
还是把文件上传到了错误的目录。
/var/www/html/web/images而不是/var/www/html/myproject/web/images。
标签: symfony file-upload