Cannot get file contents on UploadedFile Symfony

Viewed 12362

I have the following function definition:

public function save(UploadedFile $file, string $fileSystemName)
{
    $fs = $this->fileSystemMap->get($fileSystemName);

    $contents = file_get_contents($file->getRealPath());
    $filename = sprintf('%s/%s/%s/%s.%s', date('Y'), date('m'), date('d'), uniqid(), $file->getClientOriginalExtension());

    $fs->write($fileName, $contents);
}

When the code runs:

file_get_contents($file->getRealPath());

It throws an error saying:

Warning: file_get_contents(/tmp/phpM9Ckmq): failed to open stream: No such file or directory

Note that I also tried to use $file->getPathName(), but the result is just the same.

Why is this happening?

Thanks!

3 Answers

Simplest way to read content of uploaded file is :

  public function index(Request $request)
{  $raw='';

    if ($request->getMethod() == "POST") {
        $files = $request->files->all();
        foreach ($files as $file) {
            if ($file instanceof UploadedFile) {
                $raw .= file_get_contents($file->getPathname());

            }
        }

    }

    return $this->render('main/index.html.twig', [
        'controller_name' => 'MainController',
    ]);
}

your data will be stored in $raw

file_get_contents($file->getFile()->getPathname());

You can use Symfony\Component\Form\Extension\Core\Type\FileType for your file in UploadFormType

Something like:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('file', UploadFormType::class);
}

After that you can do something like this in your controller

$form = $this->get('form.factory')->create(UploadFormType::class);
$form->handleRequest($request);

$file = $form->getData();

$file will be an instance of \SplFileInfo and you can use $file->getRealPath() method.

Related