从链接获取图像(Symfony)

时间:2012-01-11 14:28:30

标签: image forms symfony1 upload

使用Symfony上传图片时遇到问题。

我有一个表单,我可以获得横幅链接,这些横幅广告托管在不同的网站上。

但是,我需要将它们保存在我的服务器上,如何在Symfony的动作类中进行保存?

谢谢

1 个答案:

答案 0 :(得分:1)

请勿使用操作,请使用表单!

您创建了一个简单的文本输入,但您使用了扩展 sfValidatorFile 的自定义验证器(用于经典文件上传)。此验证器返回 sfValidatedFile ,使用save()方法安全且非常容易保存。

以下是我自己的示例代码:

<?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);
  }
}