在开发中有时候使用上传是必不可少的,以下就详细介绍yii中的上传。
如下是表单模型:
namespace app\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; } } }
然后在html中如下:
<form action="你的url" enctype="multipart/form-data" method="post"> <input type="file" name="imageFiles[]"> <input type="submit" value="send"> </form>
控制器:
namespace app\controllers; use Yii;use yii\web\Controller; use app\models\UploadForm; use yii\web\UploadedFile;//不可少 class SiteController extends Controller{ 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]); } }
关键字词: