博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

posted on 2012-07-16 22:36  Likwo  阅读(3961)  评论(0编辑  收藏  举报