Symfony2: how to check UploadedFile without form?

I need to upload a download file from a URL to my server and save it Uploadable (DoctrineExtensions) . Almost everything works fine, my approach:

  • Upload the curl file to the temp folder on my server
  • Create an UploadedFile method and populate it with property values
  • Paste it into the downloadable Media object
  • Check execution
  • Persistent and flash

Simplified code:

 // ... download file with curl // Create UploadedFile object $fileInfo = new File($tpath); $file = new UploadedFile($tpath, basename($url), $fileInfo->getMimeType(), $fileInfo->getSize(), null); // Insert file to Media entity $media = new Media(); $media = $media->setFile($file); $uploadableManager->markEntityToUpload($media, $file); // Validate file (by annotations in entity) $errors = $validator->validate($media); // If no errors, persist and flush if(empty($errors)) { $em->persist($this->parentEntity); $em->flush(); } 

If I skip the check, everything will be fine. The file successfully moves along the right path (configured using the downloadable extension in config.yml) and is saved in the database. But checking with a manually created UploadedFile returns this error:

File could not be uploaded.

I can disable Validator to download from the URL and check the file using a custom method, but executing it using the Symfony Validator object will be a cleaner solution for me.

Is there any way to make it work?

+4
source share
1 answer

In the symfony validation component, the UploadedFile constraint internally uses this functin http://php.net/manual/es/function.is-uploaded-file.php

you can see it here https://github.com/symfony/HttpFoundation/blob/master/File/UploadedFile.php#L213

 /** * Returns whether the file was uploaded successfully. * * @return bool True if the file has been uploaded with HTTP and no error occurred. * * @api */ public function isValid() { $isOk = $this->error === UPLOAD_ERR_OK; return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname()); } 

You will need to create your own Downloadvalidator (yes, you are actually a DOWNLOADING file with curl)

+3
source

All Articles