heike2 发表于 2015-8-27 11:49:42

yii采用原始php文件上传方法上传文件

  1. 编写view
  在view的index.php 代码如下:注意action是接受文件上传的action

<form action="api/uploadimg" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />  </form>
  

  

  在Controller的action方法如下:
  

public function actionUploadimg()
    {
      $isSuc = false;
      $root = YiiBase::getPathOfAlias('webroot').Yii::app()->getBaseUrl();
      $folder = $root.'/images/images/users/4/';
      $desFilePath;
      $tmpFilePath;
      
         
      $this->mkDirIfNotExist($folder);
         
      if ((($_FILES["file"]["type"] == "image/gif")
      || ($_FILES["file"]["type"] == "image/jpeg")
      || ($_FILES["file"]["type"] == "image/png")
      || ($_FILES["file"]["type"] == "image/jpg")
      || ($_FILES["file"]["type"] == "image/pjpeg")))
      //&& ($_FILES["file"]["size"] < 20000))
      {
            if ($_FILES["file"]["error"] > 0)
            {
                $isSuc = false;
            }
            else
            {
               echo "Upload: " . $_FILES["file"]["name"] . "<br />";
                  echo "Type: " . $_FILES["file"]["type"] . "<br />";
                  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
               echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
                $tmpFilePath = $_FILES["file"]["tmp_name"];
                $desFilePath = $folder.$_FILES["file"]["name"];

                if (file_exists($desFilePath))
                {
                  unlink($desFilePath);
                  //echo $_FILES["file"]["name"] . " already exists. ";
                }
                else
                {
                  move_uploaded_file($tmpFilePath, $desFilePath);
                  $isSuc = true;
                }
            }
      }
      else
      {
            echo "Invalid file";
      }

    }
   
    function mkDirIfNotExist($dir)
    {
      
         if(!is_dir($dir))
         {
             if(!mkdir($dir, 0, true))
             {
               throw new Exception('create folder fail');
               //return false;
             }
             else
             {
               return true;
             }
         }
         return false;  }
  

  参考 http://www.w3school.com.cn/php/php_file_upload.asp
页: [1]
查看完整版本: yii采用原始php文件上传方法上传文件