使用Dropzone的多上传Symfony 2.3 [英] Multi upload Symfony 2.3 with Dropzone

查看:67
本文介绍了使用Dropzone的多上传Symfony 2.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了JQuery库的新实现: dropzone.js

I tried a new implementation of JQuery library : dropzone.js

该库提供了具有拖放解决方案的良好的多上传界面.

This library provides a good multi upload interface with drag and drop solution.

Symfony的多重上传系统似乎并不容易.

It seems that the multi upload system of Symfony isn't easy.

我遇到此错误:

Error: Cannot use object of type Symfony\Component\HttpFoundation\File\UploadedFile as array in /vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Csrf/EventListener/CsrfValidationListener.php line 87

我的实体文件:

/**
* @ORM\Entity
* @ORM\Table(name="media__file")
* @ORM\HasLifecycleCallbacks
*/
class File
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
public $id;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 */
public $name;

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

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

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()
{

    return __DIR__.'/../../../../../web/'.$this->getUploadDir();
}

protected function getUploadDir()
{

    return 'uploads/files';
}

 /**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
public function preUpload()
{
    if (null !== $this->file) {
        $this->path = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
    }
}

/**
 * @ORM\PostPersist()
 * @ORM\PostUpdate()
 */
public function upload()
{
    if (null === $this->file) {
        return;
    }


    $this->file->move($this->getUploadRootDir(), $this->path);

    unset($this->file);
}

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

我的控制器FileController:

My controller FileController :

/**
 * @Route("/admin/media/upload")
 * @Template()
 */
public function uploadsAction (){

    $file = new File();

    $form = $this->createForm(new \Tperroin\Bundle\MediaBundle\Form\FileUploadType(), $file);

    if ($this->getRequest()->isMethod('POST')) {
        $form->bind($this->getRequest());

        if ($form->isValid()) {

            $em = $this->getDoctrine()->getManager();

            $em->persist($file);
            $em->flush();

            return $this->redirect($this->generateUrl('tperroin_home_default_index'));
        }
    }

return array('form' => $form->createView());
}

最后是我的树枝模板:

<div class="widget-content">

        <form action="{{ url('tperroin_media_file_uploads') }}" method="post" {{ form_enctype(form) }} class="dropzone">

            <div class="fallback">
                <input name="file" type="file" multiple />
            </div>
        </form>

    </div>

FormType:

class FileUploadType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('file', 'file');
}
public function getName()
{
    return 'file';
}
}

我的代码有什么问题?我知道UploadedFile和数组存在问题,但我不知道该如何解决.

What is wrong with my code ? I know it's a problem with UploadedFile and array but I don't know how to resolve that.

谢谢大家!

也许此链接可以帮助某人,但我无法重现此内容:

Maybe this link can help someone, I fail to reproduce this :

在Symfony2中上载多个文件的问题

使用新的uploadAction功能进行

/**
* @Route("/upload/process", name="upload_media")
*/
   public function uploadAction()
   {
   $request = $this->get('request');
   $files = $request->files;       

   $directory = $this->get('kernel')->getRootDir() . '/../web' . $this->getRequest()->getBasePath() . '/files/';

   foreach ($files as $uploadedFile) {

       $name = $uploadedFile->getClientOriginalName();
       $file = $uploadedFile->move($directory, $name);

       $upload = new File($name);

       $em = $this->get('doctrine')->getManager();

       $em->persist($upload);

       $em->flush();


   }

   return $this->redirect($this->generateUrl('tperroin_media_default_index'));
   }

推荐答案

首先,您实际上并没有在Twig模板中使用FileUploadType.您手动创建一个表单,并将action路径设置为您在Controller中定义的url.在传递给模板的表单视图中,唯一使用的是form_enctype.但是像大多数多文件上传者一样,Dropzone似乎伪造了自己的上传图片请求.

First of all, you don't really use your FileUploadType in the Twig template. You create a form manually and set the action path to the url you defined in your Controller. The only thing you use from the form view you pass to the template is the form_enctype. But like most multi file uploaders, Dropzone seems to forge its own request to upload an Image.

这意味着您还必须手动处理传入的数据.

This means you also have to handle the incoming data manually.

/**
 * @Route("/admin/media/upload")
 * @Template()
 */
public function showUploadAction()
{
    // just show the template
    return [];
}

/**
 * @Route("/admin/media/upload/process", name="upload_media")
 */
public function uploadAction()
{
    $request = $this->get('request');
    $files = $request->files;

    // configuration values
    $directory = //...

    // $file will be an instance of Symfony\Component\HttpFoundation\File\UploadedFile
    foreach ($files as $uploadedFile) {
        // name the resulting file
        $name = //...
        $file = $uploadedFile->move($directory, $name);

        // do something with the actual file
        $this->doSomething($file);
    }

    // return data to the frontend
    return new JsonResponse([]);
}

方法uploadAction从Symfony的请求中获取FileBag,对其进行迭代,然后对结果文件执行自定义逻辑.当然,您必须自己处理File实体的存储.

The method uploadAction takes the FileBag from Symfony's request, iterates over it, and performs your custom logic on the resulting file. Of course you have to handle the storage of the File entity by yourself.

您的模板应如下所示:

<form action="{{ path('upload_media') }}" method="post" class="dropzone">
    <div class="fallback">
        <input name="file" type="file" multiple />
    </div>
</form>


由于这个问题,我注意到了Dropzone上传器,并集成了支持 OneupUploaderBundle .因此,您只需使用此捆绑包即可简化上面提到的一些步骤.


Thanks to this question I took notice of the Dropzone uploader and integrated support for it in the OneupUploaderBundle. So you could just use this bundle which simplifies a few steps mentioned above.

这篇关于使用Dropzone的多上传Symfony 2.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆