Symfony HttpFoundation UploadedFile “not uploaded due to unknown error” when using Doctrine DataFixtures

浪子不回头ぞ 提交于 2019-12-04 09:53:50

There is now a better solution:

The constructor of UploadedFile has a boolean $test parameter which disables the check using is_uploaded_file. This parameter has been added for testing/fixture code.

Just set it to true and the isValid() check of UploadedFile will not be a problem anymore.

Example:

// My data fixture code.
$test = true;
$userPhoto->setImageFile(new UploadedFile($photoDir . $photoFile, $photoFile, null, null, null, $test));

Thanks to stof, the solution is to make Attachment::setFile() (or Document::setFile() if using the cookbook example) hint for an instance of UploadedFile's parent class, Symfony\Component\HttpFoundation\File\File, and in the fixtures class, create a new instance and pass it to the setFile method

Attachment.php

<?php

namespace Acme\DemoBundle\Entity;

use Symfony\Component\HttpFoundation\File\File;
//...

class Attachment
{
    /**
     * Sets file.
     *
     * @param File $file
     */
    public function setFile(File $file = null)
    {
        $this->file = $file;
        // check if we have an old image path
        if (isset($this->path)) {
            // store the old name to delete after the update
            $this->temp = $this->path;
            $this->path = null;
        } else {
            $this->path = 'initial';
        }
    }

    //...
}

AttachmentFixtures.php

<?php

namespace Acme\DemoBundle\DataFixtures\ORM;

use Symfony\Component\HttpFoundation\File\File;
//...

class AttachmentFixtures //...
{
    //...

    public function load(ObjectManager $manager)
    {
        //...
        $imageFile = new File($pathToCopiedFile);

        $imageAttachment = new Attachment();

        $imageAttachment->setFile($imageFile);
        //...
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!