YII檔案上傳

Smile李先生發表於2016-10-20

首先我們建立model\Upload.PHP檔案

<?php  
    namespace backend\models;
    use Yii;
    use yii\web\UploadedFile;
    class Upload extends \yii\db\ActiveRecord
    {
        /**
         * @var UploadedFile|Null file attribute
         */
        public $file;
        /**
         * @return array the validation rules.
         */
        public function rules()
        {
            return [
                [["file"], "file",],
            ];
        }

下面我們看看view層是怎麼渲染的

<?php  
    use yii\widgets\ActiveForm;  
    $form = ActiveForm::begin(["options" => ["enctype" => "multipart/form-data"]]); ?>
    <?= $form->field($model, "file")->fileInput() ?>
    <button>Submit</button>
<?php ActiveForm::end(); ?>  

最後實現controller層的實現


namespace backend\controllers;
use backend\models\Upload;
use yii\web\UploadedFile;
class ToolsController extends \yii\web\Controller
{
    /**
     * 檔案上傳
     * 我們這裡上傳成功後把圖片的地址進行返回
     */
    public function actionTopic()
    {

        //例項化  
        $model=new Topic();
        if ($request->isPost)
        {
            $post=$request->post();
            $image= UploadedFile::getInstance($model, 'image');
            //檔案上傳存放的目錄  
            $dir = "../web/image/".date("Ymd");
//            var_dump($dir);die;  
            if (!is_dir($dir))
            {
                mkdir($dir);
            }else{
                //檔名  
                $fileName = date("HiiHsHis").$image->baseName . "." .$image->extension;
                //儲存路徑  
                $dir = $dir."/". $fileName;
                //儲存檔案  
                $image->saveAs($dir);
            }
        }else{

            return $this->renderPartial('save_topic',['model'=>$model]);
        }
    }
}  

相關文章