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;[...]
* @property array $file
* @property string $newFileContent
* Must be application/pdf, image/png, image/gif etc...
* @property string $contentType
* @property string $description
*/[...]
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[...]
{
$model=$this->findModel($id);
header('Content-type: application/'.$model->contentType);
echo $model->file->getBytes();
}[...]
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).[...]