繁体   English   中英

使用Symfony3上传文件无效

[英]File upload with Symfony3 not working

我正在尝试使用Symfony3上传文件,但是没有运气。 我有一个配置文件实体,它以1-1关系链接到用户实体。 该配置文件包含一个图片列。 我已经创建了一个ProfileType和Profile Model。 提交表单后,模型仅包含文件名,而没有其他内容。 $ _FILES数组也为空。 这是代码。

        $builder
        ->add("name", TextType::class, array(
        "required" => true,
    ))
        ->add("email", EmailType::class, array(
            "required" => true,
        ))
        ->add("city", TextType::class, array(
            "required" => false,
        ))
        ->add("country", ChoiceType::class, array(
            "required" => false,
        ))
        ->add("picture", FileType::class, array(
            "required" => false,
        ));



class ProfileModel
{
  private $name;
  private $email;
  private $city;
  private $country;
  private $picture;

在Controller中,我正在创建这样的表单。

$profileForm = $this->createForm(ProfileType::class, $profileModel);

当我得到图片时,它仅包含名称。

$file = $profileForm->get("picture")->getData();

呵呵rashidkhan〜

Symfony doc在上传过程中相当完整,您读过吗?
http://symfony.com/doc/current/controller/upload_file.html

进行一些修改后,我选择将其用作服务。 过程如下:

1)在app/config/config.yml添加一些参数:

parameters下:

parameters:
    locale: en
    profile_directory: '%kernel.root_dir%/../web/upload/profile'
    another_directory: '%kernel.root_dir%/../web/upload/another'

twig

twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
globals:
    profile_directory: '/upload/profile/'
    another_directory: '/upload/another/'

刚才添加的两个profile_directory将在您的上传服务和树枝中用作变量,以指向targer目录。 之后,我添加了another_directory来解释更多内容。

2)创建服务:

src/YourBundle/Services/FileUploader.php下创建一个新文件
从这里开始,我的代码与您在Symfony网站上找到的代码有所不同。

FileUploader.php内容:

<?php

namespace YourBundle\Services;

use YourBundle\Entity\ProfileModel;
use YourBundle\Entity\Another;

class FileUploader {
    private $profileDir;
    private $anotherDir;

    public function __construct($profileDir) {
        $this->profileDir=$profileDir;
        $this->anotherDir=$anotherDir;
    }

    public function upload($class) {
        if($class instanceof ProfileModel) {
            $file=$class->getPicture();
            $fileName='picture-'.uniqid().'.'.$file->guessExtension();
            $file->move($this->profileDir, $fileName);
            $class->setPicture($fileName);
        }

        if($class instanceof Another) {
            $file=$class->getPicture();
            $fileName='picture-'.uniqid().'.'.$file->guessExtension();
            $file->move($this->anotherDir, $fileName);
            $class->setPicture($fileName);
        }

        return $class;
    }
}

3)将服务注册到app/config/services.yml

services

services:
    app.file_uploader:
    class: YourBundle\Services\FileUploader
    arguments:
        - '%profile_directory%'
        - '%another_directory%'

每个参数的顺序必须与FileUploader.php文件中的private顺序相同。 这些参数是我们在app/config/config.yml下设置的parameters

4)编辑您的控制器:

控制器部分非常简单。

添加use Symfony\\Component\\HttpFoundation\\File\\File; 在导入部分

newAction

public function newAction(Request $request)
{
    $profileModel = new ProfileModel();
    $form = $this->createForm('YourBundle\Form\ProfileModelType', $profileModel);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        // We upload the file with this line
        $profileModel=$this->get('app.file_uploader')->upload($profileModel);
        $em = $this->getDoctrine()->getManager();
        $em->persist($profileModel);
        $em->flush();

        return $this->redirectToRoute('profile_model_show', array('id' => $profileModel->getId()));
    }

    return $this->render('YourBundle:Default:new.html.twig', array(
        'profileModel' => $profileModel,
        'form' => $form->createView(),
    ));
}

editAction

public function editAction(Request $request, ProfileModel $profileModel)
{
    // Add this live above everything else in the code.
    $profileModel->setPicture(new File($this->getParameter('profile_directory').'/'.$profileModel->getPicture()));
    [...]
}

我还没有走得更远,所以我只能在之后说明要修改的内容...在您的editAction ,您还必须检查$ _FILES是否为空。 如果不是,则执行上传过程。 如果是这样,请确保不要在SQL查询中编辑picture列(您将必须执行自定义查询)

5)您的树枝视图:

show.html.twig

更改

<tr>
    <th>Picture</th>
    <td>{{ profileModel.picture) }}</td>
</tr>

<tr>
    <th>Picture</th>
    <td><img src="{{ asset(profile_directory~profileModel.picture) }}"></td>
</tr>

index.html.twig 您可以将其添加(而不是替换)到edit.html.twig ,以预览实际图片。

6)说明:

app/config/config.yml我们添加了一些目录作为文件中的参数。
以后将可以根据需要更轻松地更改这些目录。 (不必编辑大量文件...是的!)
Twig目录始终从/web文件夹开始。

当我们将服务注册为arguments时,将使用这些目录。 他们将在服务文件FileUploader.php设置我们的变量。

与Symfony网站示例不同,我们将整个对象传递给上传服务。 然后,我们检查该对象是从哪个类创建的,并基于该对象执行上载过程。

然后,您在控制器中的上传过程将缩短为一行。

在树枝中,我们也将使用在设置目录变量app/config/config.yml undet的twig财产。 就像上面说的,如果我们的上传目录更改了,那么我们只需要编辑app/config/config.yml文件。


希望这可以帮助您解决上传问题。

亲切地
早熟。

你应该试试

$form = $this->createForm(ProfileType::class, $profileModel); $form->handleRequest($request); $file = $profileModel->getBrochure();

更多: http : //symfony.com/doc/current/controller/upload_file.html

伙计们,如果您想在Symfony中上载任何类型的文件,那么我有一个非常简单的解决方案,下面将对此进行介绍。 为什么我给出简单的解决方案,因为每当有新版本出现时,您都必须在services.yaml中进行一些设置,或者除了主控制器之外还必须创建其他文件。

所以解决方案是:只需在主控制器中使用move($ storing_place,$ actual_filename)函数。

将以下代码放入您的控制器文件中。

$folder_path = 'public/uploads/brochures/';
$file = $request->files->get('myfile');
$fileName = $request->files->get('myfile')->getClientOriginalName();
$file->move($folder_path, $fileName);        
return new Response($file);

希望给出的解决方案对您的项目有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM