中多文件上传的问题

中多文件上传的问题

本文介绍了Symfony2 中多文件上传的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个需要多张图片上传选项的 Symfony2 应用程序.我已经使用食谱条目上传了单个文件:如何处理使用 Doctrine 上传文件 效果很好.我已经实施了生命周期回调来上传和删除.

现在我需要把它变成一个多重上传系统.我也从 Stack Overflow 上阅读了一些答案,但似乎没有任何效果.

堆栈溢出问题:

  1. 使用 Symfony2 上传多个文件
  2. symfony 2 多文件上传

我现在有以下代码:

文件实体:

path = $path;}/*** 获取路径** @return 字符串*/公共函数 getPath(){返回 $this->path;}公共函数 getAbsolutePath(){返回 null === $this->path ?null : $this->getUploadRootDir().'/'.$this->path;}公共函数 getWebPath(){返回 null === $this->path ?null : $this->getUploadDir().'/'.$this->path;}受保护的函数 getUploadRootDir(){//上传文件保存的绝对目录路径返回 __DIR__.'/../../../../web/'.$this->getUploadDir();}受保护的函数 getUploadDir(){//去掉 __DIR__ 以便在视图中显示上传的文档/图像时不会出错.返回上传";}/*** @ORMPrePersist()* @ORMPreUpdate()*/公共函数 preUpload(){if (null !== $this->file) {//做任何你想做的事情来生成一个唯一的名字$this->path[] = uniqid().'.'.$this->file->guessExtension();}}/*** @ORMPostPersist()* @ORMPostUpdate()*/公共函数上传(){if (null === $this->file) {返回;}//如果移动文件时出现错误,则会出现异常//被 move() 自动抛出.这将适当地防止//实体在出错时被持久化到数据库$this->file->move($this->getUploadRootDir(), $this->path);未设置($this->文件);}/*** @ORMPostRemove()*/公共函数 removeUpload(){if ($file = $this->getAbsolutePath()) {取消链接($文件);}}}

文件控制器:

大批(接受"=>图片/*",多个"=>多",)))->getForm();if ($this->getRequest()->getMethod() === 'POST') {$form->bindRequest($this->getRequest());$em = $this->getDoctrine()->getEntityManager();$em->persist($file);$em->flush();$this->redirect($this->generateUrl('file_upload'));}return array('form' => $form->createView());}}

upload.html.twig:

{% 扩展 '::base.html.twig' %}{% 块体 %}<h1>上传文件</h1><form action="#" method="post" {{ form_enctype(form) }}>{{ form_widget(form.file) }}<输入类型=提交"值=上传"/></表单>{% 结束块 %}

我不知道该怎么做才能使这个工作成为一个多文件上传系统.我保留了我遵循的教程中的评论,所以我可以记住正在做什么.

更新:

新表单代码:

$images_form = $this->createFormBuilder($file)->add('文件', '文件', 数组(属性"=>大批(多个"=>多",名称" =>"文件[]",)))->getForm();

新表单树枝代码:

解决方案

这是一个已知问题 在 GitHub 上引用

一>.

正如他们所说,您应该将 [] 附加到模板中的 full_name 属性:

{{ form_widget(images_form.file, { 'full_name': images_form.file.get('full_name') ~ '[]' }) }}

I am making a Symfony2 application which needs to have a multiple image upload option. I have made the single file upload using the cookbook entry: How to handle File Uploads with Doctrine which works fine. I have implemented the lifecyclecallbacks for uploading and removing.

Now I need to turn this into a multiple upload system. I have read a few answers from Stack Overflow as well, but nothing seems to work.

Stack Overflow Question:

  1. Multiple file upload with Symfony2
  2. multiple file upload symfony 2

I have the following code at the moment:

File Entity:

<?php
namespace WebmuchProductBundleEntity;

use DoctrineORMMapping as ORM;
use SymfonyComponentValidatorConstraints as Assert;
use SymfonyComponentHttpFoundationFileUploadedFile;


/**
 * @ORMEntity
 * @ORMHasLifecycleCallbacks
 */
class File
{
    /**
     * @ORMId
     * @ORMColumn(type="integer")
     * @ORMGeneratedValue(strategy="AUTO")
     */
    public $id;

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

    /**
     * @AssertFile(maxSize="6000000")
     */
    public $file = array();

    public function __construct()
    {

    }

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

    /**
     * Set path
     *
     * @param string $path
     */
    public function setPath($path)
    {
        $this->path = $path;
    }

    /**
     * Get path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }


    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 when displaying uploaded doc/image in the view.
        return 'uploads';
    }

    /**
     * @ORMPrePersist()
     * @ORMPreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->file) {
            // do whatever you want to generate a unique name
            $this->path[] = uniqid().'.'.$this->file->guessExtension();
        }
    }

    /**
     * @ORMPostPersist()
     * @ORMPostUpdate()
     */
    public function upload()
    {
        if (null === $this->file) {
            return;
        }

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

        unset($this->file);
    }

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

FileController:

<?php

namespace WebmuchProductBundleController;

use SymfonyBundleFrameworkBundleControllerController;
use SensioBundleFrameworkExtraBundleConfigurationMethod;
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SensioBundleFrameworkExtraBundleConfigurationTemplate;

use WebmuchProductBundleEntityFile;


/**
 * File controller.
 *
 * @Route("/files")
 */
class FileController extends Controller
{
    /**
     * Lists all File entities.
     *
     * @Route("/", name="file_upload")
     * @Template()
     */
    public function uploadAction()
    {
        $file = new File();
        $form = $this->createFormBuilder($file)
            ->add('file','file',array(
                    "attr" => array(
                        "accept" => "image/*",
                        "multiple" => "multiple",
                    )
                ))
            ->getForm()
        ;

        if ($this->getRequest()->getMethod() === 'POST') {
            $form->bindRequest($this->getRequest());
                $em = $this->getDoctrine()->getEntityManager();

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

                $this->redirect($this->generateUrl('file_upload'));
        }

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

and the upload.html.twig:

{% extends '::base.html.twig' %}

{% block body %}
<h1>Upload File</h1>

<form action="#" method="post" {{ form_enctype(form) }}>

    {{ form_widget(form.file) }}

    <input type="submit" value="Upload" />
</form>
{% endblock %}

I don't know what to do to make this work as a multiple file upload system. I have kept the comments as they are from the tutorials I have followed so I can remember what is doing what.

UPDATE:

New Form Code:

$images_form = $this->createFormBuilder($file)
    ->add('file', 'file', array(
            "attr" => array(
                "multiple" => "multiple",
                "name" => "files[]",
            )
        ))
    ->getForm()
;

New Form Twig Code:

<form action="{{ path('file_upload') }}" method="post" {{ form_enctype(images_form) }}>

    {{ form_label(images_form.file) }}
    {{ form_errors(images_form.file) }}
    {{ form_widget(images_form.file, { 'attr': {'name': 'files[]'} }) }}

    {{ form_rest(images_form) }}
    <input type="submit" />
</form>
解决方案

This is a known issue as referenced on GitHub.

As they say, you should append [] to the full_name attribute in your template :

{{ form_widget(images_form.file, { 'full_name': images_form.file.get('full_name') ~ '[]' }) }}

这篇关于Symfony2 中多文件上传的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:50