6

如何将 symfony2 中的图片从表单添加到数据库。我想将徽标制作为图片字段并将项目图片从表单存储在数据库中。我该怎么做呢?

这是我的表格:

<?php

namespace Projects\ProjectsBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ProjectsType extends AbstractType
{
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
    $builder
        ->add('name')
        ->add('description')
        ->add('priority','choice', array(
'choices' => array('high' => 'high', 'low' => 'low', 'medium' => 'medium')))
        ->add('logo')
        ->add('startedAt','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;')))
        ->add('completedOn','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;')))
        ->add('createdDatetime','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;')))
        ->add('updatedDatetime','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;')))
    ;
 }

 public function setDefaultOptions(OptionsResolverInterface $resolver)
 {
    $resolver->setDefaults(array(
        'data_class' => 'Projects\ProjectsBundle\Entity\Projects'
    ));
  }

  public function getName()
  {
    return 'projects_projectsbundle_projectstype';
  }
}

这是我的控制器:

public function createAction(Request $request)
{
    $user = $this->get('security.context')->getToken()->getUser();
    $userId = $user->getId();
    $entity  = new Projects();
    $form = $this->createForm(new ProjectsType(), $entity);
    $form->bind($request);
    $entity->setCreatedBy($userId);
    $entity->setUpdatedBy($userId);
    $entity->setCompletedBy($userId);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();
    $_SESSION['projectid'] =$entity->getId();
    if($request->isXmlHttpRequest()) {
        $response = new Response();
        $output = array('success' => true, 'description' => $entity->getdescription(), 'id' => $entity->getId(), 'name' => $entity->getname(), 'priority' => $entity->getpriority(), 'logo' => $entity->getlogo(), 'startedat' => $entity->getstartedat(),'completedon' => $entity->getcompletedon(),'completedby' => $entity->getCompletedBy(), 'createdby' => $entity->getcreatedby(), 'updatedby' => $entity->getupdatedby(), 'createddatetime' => $entity->getcreateddatetime(), 'updateddatetime' => $entity->getupdateddatetime());
         $response->headers->set('Content-Type', 'application/json');
         $response->setContent(json_encode($output));
         return $response;
    }

        return $this->redirect($this->generateUrl('projects_show', array('id' => $entity->getId())));
    }

    return $this->render('ProjectsProjectsBundle:Projects:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}
4

2 回答 2

2

Symfony Docs - File Uploads with Doctrine部分很好地描述了上传文件的过程。

如果您使用了文档,为了在数据库中保存文件内容,您应该使用:

$entity->setFile(file_get_contents(<filename>));
于 2013-10-23T08:25:26.927 回答
0

将此添加到 buildform

->add('logo', 'file',array('required'=>false,'data_class' => null))

在你的控制器中

            if ($form->isValid()) {
            $file = $form['logo']->getData();
            if(!empty($file))
            {
                $dir = $this->get('kernel')->getRootDir() . 'path/to/dir/';  
                $extension = $file->guessExtension();
                $now = new \DateTime('now');
                $filename = $now->format('YmdHis').rand(1, 99999).".".$extension;
                if($file->move($dir, $filename))
                       $entity->setImage($filename);
            }

我只粘贴了相关部分

于 2013-11-04T09:43:26.723 回答