Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file to directory in yii2?

Tags:

i have an ActiveForm, and i want to add a field where the user can upload their photos. the problem is that i don't have an attribute for the image in the users table and every input field in 'yii' expects a model and an attribute as follows.

<?= $form->field($model, 'attribute')->input($platforms) ?>

i don't want to assign the image to any record nor i want to insert in in the database, i want it to be uploaded to a specific folder.

i have also checked the library kartik wrote, but also requires an attribute field.

like image 641
tareq Avatar asked May 11 '14 11:05

tareq


People also ask

How to upload file in yii2?

Uploading files in Yii is usually done with the help of yii\web\UploadedFile which encapsulates each uploaded file as an UploadedFile object. Combined with yii\widgets\ActiveForm and models, you can easily implement a secure file uploading mechanism.

How do I change the input type of a file?

<input type="file"> <input> elements with type="file" let the user choose one or more files from their device storage. Once chosen, the files can be uploaded to a server using form submission, or manipulated using JavaScript code and the File API.


2 Answers

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

<?php
use yii\widgets\ActiveForm;

$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

<?= $form->field($model, 'file')->fileInput() ?>

<button>Submit</button>

<?php ActiveForm::end(); ?>

Controller

Now create the controller that connects form and model together:

<?php
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->file = UploadedFile::getInstance($model, 'file');

        if ($model->validate()) {                
            $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
        }
    }

    return $this->render('upload', ['model' => $model]);
}
}
?>

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.

like image 108
Devy Avatar answered Sep 30 '22 16:09

Devy


in your view

use kartik\widgets\ActiveForm;
use kartik\widgets\FileInput;

$form = ActiveForm::begin(['options' => ['enctype'=>'multipart/form-data']]); //important
echo FileInput::widget([
                    'name' => 'filename',
                    'showUpload' => false,
                    'buttonOptions' => ['label' => false],
                    'removeOptions' => ['label' => false],
                    'groupOptions' => ['class' => 'input-group-lg']
                ]);
echo Html::submitButton('Submit', ['class'=>'btn btn-primary']);
ActiveForm::end();

in your controller

$file = \yii\web\UploadedFile::getInstanceByName('filename');
$file->saveAs('/your/directory/'.$file->name);
like image 25
Aditya Dharma Avatar answered Sep 30 '22 16:09

Aditya Dharma