-->

你会如何添加一个文件上传到Symfony2的DataFixture?(How would you a

2019-06-27 22:59发布

我似乎无法环绕我怎么会去有关将文件上传到DataFixture我的头。 我想上传图片的虚拟内容我的灯具加载。 这似乎喜欢的事,是需要了解的。

Answer 1:

尽管这个问题已经被问1年前似乎没有很多的信息在那里如何通过上传数据学说夹具的文件。 我只能找到这个职位。

我一直在寻找,我已经采取了比ORNJ的方式略有不同。 (可能与Symfony的的更新做的。)

我首先要

use Symfony\Component\HttpFoundation\File\UploadedFile;

然后用于复制()复制图像因为ORNJ表示将移动它。

copy($art1->getFixturesPath() . '01.jpg', $art1->getFixturesPath() . '01-copy.jpg');

然后创建并使用添加的文件:

$file = new UploadedFile($art1->getFixturesPath() . '01-copy.jpg', 'Image1', null, null, null, true);

$art1->setFile($file);

$manager->persist($art1);

“如果我因为它运行“”::灯具负载主义”时抛出一个未知的错误没有设置的最后一个参数“”真“”中的“” UploadedFile的'构造。 这个参数是“无论是测试模式被激活”。 眼看它是有意义的设置为测试模式的常客。

该方法“” getFixturesPath()“”只是检索出我的样本图像被存储的路径:

// Entity file
public function getFixturesPath()
{
    return $this->getAbsolutePath() . 'web/uploads/art/fixtures/';
}

的“” getAbsolutePath()“”方法已采取从原则文件上传 。

完整的工作代码:实体:

<?php
//src/User/MyBundle/Entity/Art.php

namespace User/MyBundle/Entity;

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

/**
 * 
 * Art Entity
 * 
 * @ORM\Entity(repositoryClass="User\MyBundle\Entity\Repository\ArtRepository")
 * @ORM\Table(name="art")
 * @ORM\HasLifecycleCallbacks
 */
class Art
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $title;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    protected $path;

    /**
     * @Assert\File(maxSize="6000000")
     */
    private $file;

    private $temp;

    public function getAbsolutePath()
    {
        return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->path;
    }

    public function getWebPath()
    {
        return null === $this->path ? null : $this->getUploadDir() . '/' . $this->path;
    }

    protected function getUploadRootDir()
    {
        // the absolute directory path where uploaded
        // documents should be saved
        return __DIR__ . '/../../../../web/' . $this->getUploadDir();
    }

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw up
        // when displaying uploaded doc/image in the view.
        return 'uploads/art';
    }

    public function getFixturesPath()
    {
        return $this->getAbsolutePath() . 'web/uploads/art/fixtures/';
    }

    /**
     * Sets file.
     *
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $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';
        }
    }

    /**
     * Get file.
     *
     * @return UploadedFile
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->getFile()) {
            // do whatever you want to generate a unique filename
            $filename = sha1(uniqid(mt_rand(), true));
            $this->path = $filename . '.' . $this->getFile()->guessExtension();
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        // the file property can be empty if the field is not required
        if (null === $this->getFile()) {
            return;
    }

        // if there is an error 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->getFile()->move($this->getUploadRootDir(), $this->path);

        // check if we have an old image
        if (isset($this->temp)) {
            // delete the old image
            unlink($this->getUploadRootDir() . '/' . $this->temp);
            // clear the temp image path
            $this->temp = null;
        }

        $this->file = null;
    }

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

夹具:

<?php
// src/User/MyBundle/DataFixtures/ORM/ArtFixtures.php

namespace User\MyBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Fredzz\LotwBundle\Entity\Art;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class ArtFixtures extends AbstractFixture implements OrderedFixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $art1 = new Art();
        $art1->setTitle('MyTitle');
        $art1->setDescription('My description');

        copy($art1->getFixturesPath() . '01.jpg', $art1->getFixturesPath() . '01-copy.jpg');
        $file = new UploadedFile($art1->getFixturesPath() . '01-copy.jpg', 'Image1', null, null, null, true);
        $art1->setFile($file);

        $art1->setUser($manager->merge($this->getReference('user-1')));

        $manager->persist($art1);
        $manager->flush();
    }
}

希望这可以帮助别人! 很抱歉,如果事情是错的。 我还在学习 :)



Answer 2:

我已经找到了答案,我的问题。 我需要使用类Symfony\Component\HttpFoundation\File\File创建一个文件。 symfony会物理移动的文件并没有那么你需要要么有每个夹具一个新的文件创建一个副本,使用使用copy()来创建一个可以代替被移动的文件的副本。

$image = new Image();
$file = new File('path/to/file.jpg');
$image->file = $file;
$om->persist($image);

类似的东西。



Answer 3:

您要使用的图像应位于您的“网络”文件夹,你应该只在您的数据灯具使用的文件指针字符串(即“/web/images/test.png”)。

通常应该避免在数据库中存储的图像。



Answer 4:

我创建了一个文件上传类PHP 5.3+

如何使用?:

文档

从RFC 3023(XML媒体类型):

顶级媒体类型“文本”,对MIME实体的一些限制,它们在[RFC2045]和[RFC2046]中描述。 特别地,UTF-16家族,UCS-4,和UTF-32是不允许的(除了通过HTTP [RFC2616],其使用MIME状机构)。

只允许YAML文件上传:

<?php
$file = new FileUpload\FileUpload();
$file->setInput( "file" );
$FileUpload->setAllowedMimeTypes(array(
    "text/x-yaml", //RFC 3023
    "application/x-yaml", // Ruby on Rails
    "text/plain",//Possible option( only text plain )
    "text/yaml",//Possible option
    "text/x-yaml",//Possible option
    "application/yaml",//Possible option
));
$file->setDestinationDirectory("/var/www/html/myapp/");
$file->save();
if ($file->getStatus()) {
    echo "Okay";
}
?>

与所有MIME类型示例:

<?php
$file = new FileUpload\FileUpload();
$file->setInput( "file" );
$file->save();
if ($file->getStatus()) {
    echo "is Upload!";
}
?>
<html>
    <head>
        <title>FileUpload Example</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
        <form method="post" action="" enctype="multipart/form-data">
            <input type="file" name="file" />
            <input type="submit" value="Upload now!" />
        </form>
    </body>
</html>

GitHub上: https://github.com/olaferlandsen/FileUpload-for-PHP



文章来源: How would you add a file upload to a Symfony2 DataFixture?