2016-09-13 29 views
0

我刚开始学习Symfony 3并且我做了一个博客。 我使用Doctrine Entities与数据库进行交互。我在Mac OS上使用Xampp。Symfony 3不能移动上传的文件

我创建了一个带有文件输入的表单,但是当我想上传文件时,它永远不会移动到它应该在的位置,并且在数据库中记录Xampp的临时文件夹的路径。

这里的代码在实体文件中的一部分:

public function getFile() 
{ 
    return $this->file; 
} 

public function setFile(UploadedFile $file = null) 
{ 
    $this->file = $file; 
} 

public function upload(){ 
    if(null === $this->file){ 
    return; 
    } 
    $name = $this->file->getClientOriginalName(); 

    $this->file->move($this->getUploadRootDir(), $name); 
    $this->image = $name; 
} 

public function getUploadDir(){ 
    return 'uploads/img'; 
} 

public function getUploadRootDir(){ 
    return '/../../../../web/'.$this->getUploadDir(); 
} 

这是我的表单生成器:

class BlogType extends AbstractType 
{ 
    /** 
    * @param FormBuilderInterface $builder 
    * @param array $options 
    */ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('image', FileType::class) 
      ->add('categorie', TextType::class) 
      ->add('photographe', TextType::class) 
      ->add('save', SubmitType::class) 
     ; 
    } 

    /** 
    * @param OptionsResolver $resolver 
    */ 
    public function configureOptions(OptionsResolver $resolver) 
    { 
     $resolver->setDefaults(array(
      'data_class' => 'Boreales\PlatformBundle\Entity\Blog' 
     )); 
    } 
} 

而从控制器的addAction:

public function addAction(Request $request) 
{ 
    //Création de l'entité 
    $photo = new Blog(); 
    $form = $this->get('form.factory')->create(BlogType::class, $photo); 

    if($request->isMethod('POST') && $form->handleRequest($request)->isValid()){ 
    $photo->upload(); 


    $em = $this->getDoctrine()->getManager(); 
    $em->persist($photo); 
    $em->flush(); 

    $request->getSession()->getFlashBag()->add('notice', 'Photo enregistrée.'); 
    var_dump($photo->getImage()); 
    //return new Response('Coucou'); 
    //return $this->redirectToRoute('galerie'); 
    } 
    return $this->render('BorealesPlatformBundle:Blog:add.html.twig', array(
    'form' => $form->createView() 
)); 
} 

有人可以看到问题在哪里吗?

回答

2

该代码通常是确定的,但是您的path有问题。

你现在有这样的路径

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

删除前导斜线从它

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

正斜杠在开始的时候是目录。你不能超越,它在顶层。

但是,这也不会工作,因为你需要一个绝对路径到你的目录。要做到这一点,最好的办法就是这个上传目录添加到config.yml

# app/config/config.yml 

# ... 
parameters: 
    upload_directory: '%kernel.root_dir%/../web/uploads/img' 

,然后使用它。但是由于其设计原因,您无法直接从模型层访问这些参数。所以你需要将它传递给你所调用的方法。

//your controller 
$photo->upload($this->getParameter('upload_directory')); 

所以,你将有你在实体法样子

public function upload($path){ 
    if(null === $this->file){ 
     return; 
    } 
    $name = $this->file->getClientOriginalName(); 

    $this->file->move($path, $name); 
    $this->image = $name; 
} 

这将是最好的,最合适的方式,做你想做的事情。希望能帮助到你!