2017-06-29 171 views
1

我使用这个表单来选择一个文件,我不知道如何才能得到这个文件在我的PHP函数的路径。Symfony获取文件路径

<form class="dropzone"> 

    <input name="file" type="file" multiple /> 

</form> 

我想要得到的路径,把它放在一个变量,并用它来阅读CSV文件,如:

public function importAction(Request $request) 

{ 

    $myFilePath = ''; //what should i do here? 

    $csv = Reader::createFromPath($myFilePath); // I use it now like this '../path/myFile1.csv' 

} 

任何帮助,将不胜感激。

回答

1

我强烈建议在你的Action函数中使用Form。

使用表单是处理Symfony中表单(和文件)提交的最佳方式。

欲了解更多信息,请查看此链接: https://symfony.com/doc/current/reference/forms/types/file.html

例如:

控制器:

/** 
* @Route("/test",name="dashboard_test") 
* @Template() 
*/ 
public function testAction(Request $request) 
{ 
    $form = $this->createFormBuilder() 
     ->add('files', FileType::class) 
     ->add('save', SubmitType::class, array('label' => 'Create Post')) 
     ->getForm(); 

    $form->handleRequest($request); 
    if ($form->isSubmitted() && $form->isValid()) 
    { 
     $someNewFilename = 'test.pdf'; 
     $dir = '/Users/'; 
     $form['files']->getData()->move($dir, $someNewFilename); 

     // done 
    } 


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

视图(树枝):

{{ form_start(form) }} 
{{ form_widget(form) }} 
{{ form_end(form) }} 
+0

这是不完整的解决方案,我不想保存文件,我只是想获得选择路径。 –

+0

您可以使用$ dir变量来获取路径 –