Reputation: 13
I have a problem to upload an image using Symfony.
I have a form where I get the links of banners, those banners are hosted on different websites.
But, I need to save them on my server, how to do it in an action class in Symfony?
Thank you
Upvotes: 0
Views: 412
Reputation: 5882
Don't use an action, use a form!
You create a simple text input, but you use a custom validator extending the sfValidatorFile (used for classic file upload). This validator is returning a sfValidatedFile, safe and really easy to save with the save() method.
Here is an example code of my own:
<?php
/**
* myValidatorWebFile simule a file upload from a web url (ftp, http)
* You must use the validation options of sfValidatorFile
*
* @package symfony
* @subpackage validator
* @author dalexandre
*/
class myValidatorWebFile extends sfValidatorFile
{
/**
* @see sfValidatorBase
*/
protected function configure($options = array(), $messages = array())
{
parent::configure($options, $messages);
}
/**
* Fetch the file and put it under /tmp
* Then simulate a web upload and pass through sfValidatorFile
*
* @param url $value
* @return sfValidatedFile
*/
protected function doClean($value)
{
$file_content = file_get_contents($value);
if ($file_content)
{
$tmpfname = tempnam("/tmp", "SL");
$handle = fopen($tmpfname, "w");
fwrite($handle, $file_content);
fclose($handle);
$fake_upload_file = array();
$fake_upload_file['tmp_name'] = $tmpfname;
$fake_upload_file['name'] = basename($value);
return parent::doClean($fake_upload_file);
}
else
{
throw new sfValidatorError($this, 'invalid');
}
}
/**
* Fix a strange bug where the string was declared has empty...
*/
protected function isEmpty($value)
{
return empty ($value);
}
}
Upvotes: 1