Changes
Title
unchanged
Upload files in Yii2 with MongoDb and GridFs
Category
unchanged
How-tos
Yii version
changed
2.0
Tags
changed
File upload,yii2, mongodb, gridfs, File upload
Content
changed
[...]
### 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>[...]