繁体   English   中英

Symfony 3无法移动上传的文件

[英]Symfony 3 can't move uploaded file

我刚刚开始学习Symfony 3,并创建了一个博客。 我使用学说实体与数据库进行交互。 我在Mac OS上使用Xampp。

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

这是实体文件中的代码部分:

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()
  ));
}

有人可以看到问题所在吗?

该代码总体上还可以,但是您的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'));

因此,您将使Entity中的方法看起来像

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

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

那将是做您想做的最好和最合适的方法。 希望能帮助到你!

暂无
暂无

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

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