yii文件上传

1.创建 模型如下:

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/7/26
 * Time: 20:14
 */
namespace app\modules\forum\models;

use yii\base\Model;
use yii\web\UploadedFile;


class UploadForm extends Model
{
    public $file;

    public function rules(){
        return [
            [['file'],'file'],//可以将验证规则写的更加具体
        ];
    }
}


2.视图:

<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/7/26
 * Time: 20:17
 */
use yii\widgets\ActiveForm;

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

3.控制器

3.1.单图片(文件)上传控制器代码:

public function actionUpload(){
		//echo Yii::$app->basePath;exit();
		$model = new UploadForm();
		if(Yii::$app->request->isPost){
			$model->file = UploadedFile::getInstance($model,'file');//获取上传文件实例
			if($model->validate()){
				$model->file->saveAs(Yii::$app->basePath.'/modules/uploads/'.$model->file->baseName.'.'.$model->file->extension);
			}
		}
		return $this->render('upload',['model'=>$model]);
	}




3.2.多图片(文件)上传控制器代码:

public function actionUploads(){
		$model = new UploadForm();
		if(Yii::$app->request->isPost){
			$files = UploadedFile::getInstances($model,'file');
			foreach($files as $file){
				$_model = new UploadForm();
				$_model->file = $file;
				if($_model->validate()){
					$_model->file->saveAs(Yii::$app->basePath.'/modules/uploads/'.$_model->file->baseName.'.'.$_model->file->extension);
				}else {
					foreach($_model->getErrors('file') as $error){
						$model->addError('file',$error);
					}
				}
			}
			if($model->hasErrors('file')){
				$model->addError(
						'file',
						count($model->getErrors('file')).'of'.'files not uploaded'
				);
			}

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

注意在使用前,先要引入UploadFile类:
use yii\web\UploadedFile;

好了,现在就可以实现你的图片(文件)上传了!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值