Upload files in Yii2 with MongoDb and GridFs

Comparing #10 with #12

Yii version

2.0

Tags

File upload,yii2, mongodb, gridfs, File upload

Content

[...]
### Step 1: the model

Depending on your type of application (advanced or basic), create a new model **Asset** in **app\models** or, **backend\models** / **frontend\models** **common\models**.


```php

namespace common\models;
[...]
In _form.php (format as you like, in this case there's no html because I put this form in a modal with custom html and tags that can be confusing for the sake of the tutorial)


```php
<?php use yii\helpers\Html;
 
use yii\widgets\ActiveForm;
 
 
$form = ActiveForm::begin([
'options'=>['enctype'=>'multipart/form-data']]);?>
[...]
Now, the interesting part:

```php
use yii\web\UploadedFile;  
use common\models\Asset;


public function actionCreate()
[...]
Name this action as you like. Basically this is the action that will render the file; now you'll see the reason of that "contentType" attribute.


```php

/**
* Displays the asset as a blob
[...]
In order to render the file - let's say, an image - , apply this code in any view:


```php

use yii\helpers\Html;
use yii\helpers\Url;
[...]

```php

use yii\helpers\Html;
use yii\helpers\Url;

<?php if(strpos($model->contentType,'image')===false): //Not an image?>
<iframe src="<?=Url::to(['asset/get', 'id'=>(string)$model->_id]);?>" width="100%" height="600px"></iframe>
[...]