Monday, January 25, 2010

Uploading a File in Symfony 1.4

Being new with Symfony, I decided to learn on their most recent stable version (1.4). For my work, I needed to be able to upload a file from the user when they submitted a form. While reviewing the Jobeet tutorial they have posted to help users learn Symfony, I found this:
sfValidatorFile is quite interesting as it does a number of things:
  • Validates that the uploaded file is an image in a web format (mime_types)
  • Renames the file to something unique
  • Stores the file in the given path
  • Updates the logo column with the generated name
 My implementation was in fact using sfValidatorFile to validate the file's mime type, etc. Trusting this to be as the documentation said it is, I looked for every other possible reason why my files wouldn't upload.

Problem:
Files wouldn't upload properly in Symfony 1.4 even with using the sfValidatorFile.

Solution:
Manually loop over and move files to the upload directory.

The code I used in my actions file was like this:

if ($this->form->isValid())
        {
            foreach ($request->getFiles($this->form->getName()) as $uploadedFile)
              {
                $uploadDir = sfConfig::get('sf_upload_dir') . '/assets';
                move_uploaded_file($uploadedFile["tmp_name"], $uploadDir . "/" . $uploadedFile["name"] );
            }
            $this->redirect('media/thumbnailSelector?'.http_build_query($this->form->getValues()));
        }
I hope this helps someone figure out their code issues.

Happy coding.

3 comments:

Daniel said...

You are my hero of the day, thanks!

John Reidy said...

Hi,
I looked at this as well, with version version: 1.4.11
I was able to use the file validator in the admin generated backend.
In the doSave method of the generated formclass I had


$file = $this->getValue('image'); //tbs - change to image1, image2...
if ( $file )
{
$filename = sha1($file->getOriginalName().microtime().rand()).$file->getExtension($file->getOriginalExtension());

$savedName = $file->save($uploadDestPath . $filename);
$newSavedName = $file->setSavedName( $filename);

Where file is a sfValidatedFile object.
the $file->save call works, however it saved the value to the database with the entire file system path.
I added a call setSavedName to just set it as the name I want.

Brent Anderson said...

@Daniel yeah, he gets the hero award from me too. This just saved me tons of time.