Symfony2 - 2.6 文件上传

Symfony2 - 2.6 file uploads

我在 2.6 上上传文件时遇到问题,这在以前的版本上运行良好。我不知道问题出在哪里,没有错误,当我转储 post 对象时,我在那里看到一个文件名,但图像文件夹中没有文件。

我的图片文件夹在 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 %}

Post实体

/**
 * @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);
    }
}

只需更改您的实体即可。

而不是

public function getUploadDir()
{
    return 'images/';
}

替换此

public function getUploadDir()
{
    return '/images';
}

您的实体路径是:

var/www/html/myproject/src/AppBundle/Entity/Post.php

和您的 getUploadRootDir 方法:

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

这将返回四次,因为有 4(../) 将您带出源目录。

用这个来解决这个错误:

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