2013-05-20 103 views
3

我有一个上传表单,它工作的很好,照片正在上传,但问题是,sfThumbnail插件似乎不工作。没有缩略图正在生成。这里是我的代码:Symfony 1.4 sf缩略图不生成缩略图

 // /lib/form/UploadForm.class.php 

     public function configure() 
     { 
     $this->setWidget('photo', new sfWidgetFormInputFileEditable(
     array(
     'edit_mode' => !$this->isNew(), 
     'with_delete' => false, 
     'file_src' => '', 
     ) 
    )); 

     $this->widgetSchema->setNameFormat('image[%s]'); 

     $this->setValidator('photo', new sfValidatorFile(
     array(
     'max_size' => 5000000, 
     'mime_types' => 'web_images', 
     'path' => '/images/', 
     'required' => true, 
     'validated_file_class' => 'sfMyValidatedFileCustom' 
      ) 
     )); 

而这里的验证器类

class sfMyValidatedFileCustom extends sfValidatedFile{ 

    public function save($file = null, $fileMode = 0666, $create = true, $dirMode = 0777) 
    { 
     $saved = parent::save($file, $fileMode, $create, $dirMode); 
     $thumbnail = new sfThumbnail(150, 150, true, true, 75, ''); 
     $location = strpos($this->savedName,'/image/'); 
     $filename = substr($this->savedName, $location+15); 
     // Manually point to the file then load it to the sfThumbnail plugin 
     $uploadDir = sfConfig::get('sf_root_dir').'/image/'; 
     $thumbnail->loadFile($uploadDir.$filename); 
     $thumbnail->save($uploadDir.'thumb/'.$filename,'image/jpeg'); 
     return $saved; 
    } 

而且我的行动代码:

public function executeUpload(sfWebRequest $request) 
    { 
    $this->form = new UploadForm(); 
    if ($request->isMethod('post')) 
    { 
     $this->form->bind(
     $request->getParameter($this->form->getName()), 
     $request->getFiles($this->form->getName()) 
    ); 
     if ($this->form->isValid()) 
     { 
      $this->form->save(); 
      return $this->redirect('photo/success'); 
     } 
    } 
    } 

我不是100%肯定,如果我做正确,但这是我从文档和其他例子中看到的。

回答

3

您不能使用$this->savedName,因为它是来自sfValidatedFile的受保护值。您应该改用$this->getSavedName()。你为什么要提取的文件名的时候,终于,你loadFile重新添加/image/到它时,它负载

$location = strpos($this->savedName,'/image/'); 
$filename = substr($this->savedName, $location+15); 

我不明白这个部分?

无论如何,我对你的班级做了一些改变。我没有测试它,但我认为它应该工作。

class sfMyValidatedFileCustom extends sfValidatedFile 
{ 
    public function save($file = null, $fileMode = 0666, $create = true, $dirMode = 0777) 
    { 
    $saved = parent::save($file, $fileMode, $create, $dirMode); 
    $filename = str_replace($this->getPath().DIRECTORY_SEPARATOR, '', $saved); 

    // Manually point to the file then load it to the sfThumbnail plugin 
    $uploadDir = $this->getPath().DIRECTORY_SEPARATOR; 

    $thumbnail = new sfThumbnail(150, 150, true, true, 75, ''); 
    $thumbnail->loadFile($uploadDir.$saved); 
    $thumbnail->save($uploadDir.'thumb/'.$filename, 'image/jpeg'); 

    return $saved; 
    } 
+0

非常感谢j0k!你是一个拯救生命的人!感谢您的详细解释。我一定会记住这一点。 – kevin