Ton Gok
Ton Gok

Reputation: 152

Symfony get File path

I use this form to select a file, i wonder how could i get only the path of this file in my php function.

<form class="dropzone">

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

</form>

I want to get the path to put it in a variable and use it to read CSV Files like:

public function importAction(Request $request)

{

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

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

}

Any help would be appreciated.

Upvotes: 1

Views: 3084

Answers (1)

Ron Fridman
Ron Fridman

Reputation: 304

I highly suggested using Form in your Action function.

Using form is the best way to handle form (and file) submission in Symfony.

For more information check out this link: https://symfony.com/doc/current/reference/forms/types/file.html

example:

Controller:

/**
 * @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()
    ];
}

View (twig):

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

Upvotes: 2

Related Questions