Question

if I print the content of an instance of UploadedFile, this is what I get

array (
  'opt_image_header' => 
     Symfony\Component\HttpFoundation\File\UploadedFile::__set_state(array(
       'test' => false,
       'originalName' => 'triangle-in-the-mountains.jpg',
       'mimeType' => 'image/jpeg',
       'size' => 463833,
       'error' => 0,
)

And this is how I get the uploaded file in the Controller. Before of moving it, I should resize it.

  foreach($request->files as $uploadedFile){

      $ext = '.' . $uploadedFile['opt_image_header']->guessExtension();
      $filename = sha1(uniqid(mt_rand(), true)) . $ext;

      $uploadedFile['opt_image_header']->move($path . '/images/', $filename);

  }

so there's no the "tmp_name" that I'd need for resizing the image before of saving it.

Do I need to read it directly from the $_FILE array?

Was it helpful?

Solution

Use $uploadedFile->getRealPath()

Symfony\Component\HttpFoundation\File\UploadedFile extends Symfony\Component\HttpFoundation\File\File, which extends PHP's SplFileInfo, so UploadedFile inherits all methods from SplFileInfo.

Use $uploadedFile->getRealPath() for the absolute path for the file. You can also use other methods on it, such as getFilename() or getPathname(). For a complete list of available methods (of SplFileInfo), see the docs.

Symfony's File class adds some extra methods, such as move() and getMimeType(), and adds backward compatibility for getExtension() (which was not available before PHP 5.3.6). UploadedFile adds some extra methods on top of that, such as getClientOriginalName() and getClientSize(), which provide the same information as you would normally get from $_FILES['name'] and $_FILES['size'].

OTHER TIPS

If you are uploading a file with Doctrine, take a look at Symfony Documentation Upload a file
If you want to upload a file without Doctrine, you can try something like:

foreach($request->files as $uploadedFile) {
    $filename = $uploadedFile->get('Put_Input_Name_Here')->getClientOriginalName();
    $file = $uploadedFile->move($distination_path, $filename);
}

If there was any issue for uploading file move() will throw an exception

UPDATED
According to get the temp path of the uploaded file to resize the image you can use getPath() function in the mentioned loop

$tmp_name = $uploadedFile->get('Put_Input_Name_Here')->getPath();

If you ask why, because the Symfony File class is extends SplFileInfo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top