代码在 http://www.yiichina.com/doc/guide/2.0/input-file-upload
111.创建model
<?php /** * Created by PhpStorm. * User: xx * Date: 2017/2/14 * Time: 8:49 */ namespace frontend\models; use yii\base\Model; use yii\web\UploadedFile; class UploadForm extends Model { /** * @var UploadedFile[] */ public $imageFiles; public function rules() { return [ [['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4], ]; } public function upload() { if ($this->validate()) { foreach ($this->imageFiles as $file) { $file->saveAs('uploads/' . $file->baseName . '.' . $file->extension); } return true; } else { return false; } } } 222.创建controller
<?php namespace frontend\controllers; use Yii; use yii\web\Controller; use frontend\models\UploadForm; use yii\web\UploadedFile; class UploadController extends Controller { public function actionIndex(){ $model = new UploadForm(); return $this->render('upload', ['model' => $model]); } public function actionUpload() { $model = new UploadForm(); if (Yii::$app->request->isPost) { $model->imageFiles = UploadedFile::getInstances($model, 'imageFiles'); if ($model->upload()) { // 文件上传成功 return; } } return $this->render('upload', ['model' => $model]); } }333.创建view
<?php use yii\widgets\ActiveForm; ?> <?php $form = ActiveForm::begin([ 'action' => ['upload/upload'], 'options' => ['enctype' => 'multipart/form-data']]) ?> <?= $form->field($model, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?> <button>Submit</button> <?php ActiveForm::end() ?>
上传可能出现错误,需开扩展
php_fileinfo