4

在发布此问题之前,我已经尝试了 4 次,但没有运气。

我仔细阅读了文档,在安装 VichUploaderBundle 后,我创建了上传歌曲的代码,如下所示:

实体/模型

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @ORM\Entity
 * @Vich\Uploadable
 */
class Song
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    // ..... other fields

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     * 
     * @Vich\UploadableField(mapping="song_track", fileNameProperty="trackName")
     * 
     * @var File
     */
    private $trackFile;

    /**
     * @ORM\Column(type="string", length=255)
     *
     * @var string
     */
    private $trackName;

    /**
     * @ORM\Column(type="datetime")
     *
     * @var \DateTime
     */
    private $updatedAt;

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the  update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     *
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $trackName
     */
    public function setTrackFile(File $trackName = null)
    { 
        $this->$trackName = $trackName;
        if ($trackName) {
          var_dump($trackName);
            // It is required that at least one field changes if you are using doctrine
            // otherwise the event listeners won't be called and the file is lost
            $this->updatedAt = new \DateTime('now');
        }
    }

    /**
     * @return File
     */
    public function getTrackFile()
    {
        return $this->trackFile;
    }

    /**
     * @param string $imageName
     */
    public function setTrackName($trackName)
    {
        $this->trackName = $trackName;
    }

    /**
     * @return string
     */
    public function getTrackName()
    {
        return $this->trackName;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     *
     * @return Track
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}

控制器

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Song;

class UploadTrackController extends Controller
{
    /**
     * @Route("/uploadtrack", name="uploadtrackform")
     */
    public function indexAction(Request $request)
    {
      $track = new Song();
      $form = $this->createFormBuilder($track)
          ->add('trackFile', 'file')
          ->add('save', 'submit', array('label' => 'Upload File'))
          ->getForm();
        $form->handleRequest($request);

        return $this->render('default/uploadtrack.html.twig', 
          array(
            'form' => $form->createView(),
          )
        );
    }
}

看法

<body>
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</body>

我可以看到表单,上传文件并正确触发控制器。我没有收到任何错误,但既没有将文件复制到文件夹中,也没有将数据保存到数据库中。

您可以在我的实体中看到我有一个 var_dump 它实际上包含一个错误属性。提交表单后,这就是我从该 var_dump 中得到的:

对象(Symfony\Component\HttpFoundation\File\UploadedFile)#13 (7) { ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> bool(false) ["originalName":"Symfony \Component\HttpFoundation\File\UploadedFile":private]=> string(24) "file.pdf" ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(15) "application /pdf" ["size":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(186992) ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int (0) ["路径名":"SplFileInfo":private]=> 字符串(66)"/private/var/folders/1g/4t5n9rhj0_s_9tnstpjj6w_w5wl8pn/T/phpptwjZH" ["文件名":"SplFileInfo":private]=> 字符串(9) "phpptwjZH" }

在我看来,该文件暂时存储在某处,但从未复制到文件夹中,因此学说不会将任何数据保存到数据库中。

对不起,如果我没有找到更简洁的方法,但这个问题主要是针对那些有 Symfony 和 VichUploaderBundle 经验的人。

先感谢您

以防万一您想知道捆绑包的配置是什么,我们开始吧:

#VichUpload config
vich_uploader:
    db_driver: orm # or mongodb or propel or phpcr
    mappings:
        song_track:
            uri_prefix:         /upload/tracks
            upload_destination: %kernel.root_dir%/../web/upload/tracks

更新

像下面建议的 K-Phoen 一样在 Song 实体中修改了 setter,仍然是同样的问题:/ PS:我正在使用 Symfony 内部服务器 php app/console server:run 运行项目

public function setTrackFile(File $trackFile = null)
{
    $this->trackFile = $trackFile;
    if($trackFile){
      var_dump($trackFile);
        // It is required that at least one field changes if you are using doctrine
        // otherwise the event listeners won't be called and the file is lost
        $this->updatedAt = new \DateTime('now');
    }
}

更新 2

将它添加到我的控制器使整个工作正常,文件被复制,数据库被写入......

 if ($form->isValid()) {
    $em = $this->getDoctrine()->getManager();
    $em->persist($track);
    $em->flush();
}

...顺便说一句,我在阅读 VichUploaderBundle 文档后感到困惑,因为我了解到这种持久化是自动调用的,无需指定任何其他内容,然后 $form->handleRequest($request); 在控制器中。

4

1 回答 1

0

setTrackFile(…)setter 不正确:它应该更新trackFile属性而不是trackName.

public function setTrackFile(File $trackFile = null)
{
    $this->trackFile = $trackFile;

    // …
}
于 2015-10-29T21:22:33.183 回答