How to upload a file to directory in yii2?-open source projects yiisoft/yii2

Devy

Follow the official documentation

https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md

Form Model

namespace app\models;

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

/**
* UploadForm is the model behind the upload form.
*/
class UploadForm extends Model
{
/**
 * @var UploadedFile|Null file attribute
 */
public $file;

/**
 * @return array the validation rules.
 */
public function rules()
{
    return [
        [['file'], 'file'],
    ];
}
}
?>

Form View





Submit


Controller

Now create the controller that connects form and model together:


Instead of model->load(...) we are using UploadedFile::getInstance(...). [[\yii\web\UploadedFile|UploadedFile]] does not run the model validation. It only provides information about the uploaded file. Therefore, you need to run validation manually via $model->validate(). This triggers the [[yii\validators\FileValidator|FileValidator]] that expects a file:

 $file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE //in code framework

If validation is successful, then we’re saving the file:

 $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);

If you’re using “basic” application template then folder uploads should be created under web.

That’s it. Load the page and try uploading. Uplaods should end up in basic/web/uploads.