Difference between #7 and #12 of
Upload files in Yii2 with MongoDb and GridFs

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;
 
<?= Html::img(Html::urlUrl::to(['asset/get', 'id'=>(string)$model->_id]), ['alt'=>$model->description]);?>

```
[...]

```php
 
use yii\helpers\Html;
 
use yii\helpers\Url;
 
<?php if(strpos($model->contentType,'image')===false): //Not an image?> <iframe src="<?=Html::urlUrl::to(['asset/get', 'id'=>(string)$model->_id]);?>" width="100%" height="600px"></iframe> <?php else: ?> <?= Html::img(Html::urlUrl::to(['asset/get', 'id'=>(string)$model->_id]), ['alt'=>$model->description]);?>
<?php endif; ?>
```

Quick note: this method is **recommended** for all of you guys who have to store sensible user data files (like card IDs, passports and so on) because you can leverage the standard **AccessControl** rules to display a single file so that you can put granular permissions to CRUD operations regarding files too (especially to read operations). If you are thinking of storing your user files in the server and you are not sure of how an .htaccess or apache2.conf file works, then I recommend this method (search engines crawlers can be very nasty when you publish /your/folder/image.png and you forget to remove the "List" permissions).
[...]
6 0
6 followers
Viewed: 37 321 times
Version: 2.0
Category: How-tos
Written by: edoardo849
Last updated by: pceuropa
Created on: Feb 9, 2014
Last updated: 4 years ago
Update Article

Revisions

View all history