【问题标题】:Get image from link (Symfony)从链接获取图像(Symfony)
【发布时间】:2012-02-07 21:47:48
【问题描述】:

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

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

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

谢谢

【问题讨论】:

    标签: image forms symfony1 upload


    【解决方案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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多