Uploading files
Handling file uploads is a pretty common task for a web application. Yii has some helpful classes built in to do this. Let's create a simple form that will allow the upload of ZIP archives and store them in /uploads
.
Getting ready
Create a new application by using the Composer package manager, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.
Create the
@app/web/uploads
directory.
How to do it...
We will start with the model, so create the
@app/models/Upload.php
model as follows:<?php namespace app\models; use yii\base\Model; use yii\web\UploadedFile; class UploadForm extends Model { /** * @var UploadedFile */ public $file; public function rules() { return [ ['file', 'file', 'skipOnEmpty' => false, 'extensions' => 'zip'], ]; } public function upload() { if ($this->validate()) { $this->file->saveAs('uploads/' . $this->file...