16

ファイルのアップロードを DataFixture に追加する方法について頭を悩ませているようには見えません。フィクスチャがロードするダミー コンテンツの画像をアップロードしようとしています。これは知っておくと何かと重宝しそうです。

4

4 に答える 4

21

この質問は 1 年前に尋ねられましたが、doctrine データフィクスチャを介してファイルをアップロードする方法については、あまり情報がないようです。この投稿しか見つかりませんでした。

私は探してきましたが、ornj とは少し異なるアプローチをとっています。(Symfony の更新に関係している可能性があります。)

私は最初にしなければならなかった

use Symfony\Component\HttpFoundation\File\UploadedFile;

そして、ornjが言ったように移動するため、copy()を使用して画像をコピーしました。

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);

「Doctrine:fixtures:load」の実行時に不明なエラーがスローされるため、「UploadedFile」コンストラクターで最後のパラメーターを「true」に設定しなかった場合。このパラメータは「テストモードがアクティブかどうか」です。それがフィクスチャであることを考えると、テストモードに設定するのは理にかなっています。

メソッド「getFixturesPath()」は、サンプル画像が保存されているパスを取得するだけです。

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

「getAbsolutePath()」メソッドはDoctrine File Uploadsから取得されました。

完全な作業コード: エンティティ:

<?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();
    }
}

これが誰かを助けることを願っています! 何か間違っていたらごめんなさい。まだ勉強してる :)

于 2013-09-18T22:23:37.997 に答える
9

私は自分の質問に対する答えを見つけました。クラスSymfony\Component\HttpFoundation\File\Fileを使用してファイルを作成する必要があります。Symfony はファイルを物理的に移動し、コピーを作成しないため、フィクスチャごとに新しいファイルを作成するか、 use を使用copy()して移動可能なファイルのコピーを作成する必要があります。

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

そんな感じ。

于 2012-09-07T13:54:17.440 に答える
0

使用したい画像は「Web」フォルダにある必要があり、データ フィクスチャではファイル ポインタ文字列 (つまり「/web/images/test.png」) のみを使用する必要があります。

通常、データベースに画像を保存することは避けてください。

于 2012-09-07T03:12:07.253 に答える