首页 文章

Symfony VichUploaderBundle不上传文件也不写入数据库

提问于
浏览
1

在发布此问题之前,我一直在尝试4次而没有运气 .

我仔细阅读了文档,安装完VichUploaderBundle之后,我创建了我的代码来上传一首歌,如下所示:

Entity/Model

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

Controller

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

View

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

我可以看到表单,上传文件并正确触发控制器 . 我没有收到任何错误,但文件没有复制到文件夹中或数据持久存储到数据库 .

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

object(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)[“pathName”:“SplFileInfo”:private] => string(66)“/ private / var / folders / 1g / 4t5n9rhj0_s_9tnstpjj6w_w5wl8pn / T / phpptwjZH”[“fileName”:“SplFileInfo”:private] => string(9)“phpptwjZH”}

在我看来,文件暂时存储在某个地方但从未复制到文件夹中,因此没有数据通过doctrine持久保存到db .

很抱歉,如果我没有找到更简洁的方法,但这个问题主要针对那些有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

UPDATE

宋实体中的修改后的setter就像下面提到的K-Phoen一样,还是同样的问题:/ PS:我正在使用Symfony内部服务器php app / console服务器运行项目:运行

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

UPDATE 2

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

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

...顺便说一句,我在这一点上感到困惑,因为我读了VichUploaderBundle文档,我知道这个持久化是自动调用的,无需另外指定任何其他的$ form-> handleRequest($ request);在控制器中 .

1 回答

  • 0

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

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

相关问题