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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM