This extension does not contain any widget for ajax upload.
You can to use any widget, for example: fileapi-widget-yii2
But what is important, is that the input value should contain the id of a file or an array of ids.
For example, we have a model News
, and we want to add the ability to upload files.
Let's do it.
-
Configuring components
'fileManager' => [ 'class' => 'rkit\filemanager\FileManager', // 'sessionName' => 'filemanager.uploads', ], // any flysystem component for storage, for example https://github.com/creocoder/yii2-flysystem 'localFs' => [ 'class' => 'creocoder\flysystem\LocalFilesystem', 'path' => '@webroot/uploads', ],
-
Creating migrations
Migration for a model
File
(and of course you need to create the model)php yii migrate/create create_file_table --fields="title:string:notNull:defaultValue(''),name:string:notNull:defaultValue(''),date_create:timestamp,date_update:timestamp"
You can add any extra fields, such as
user_id
,ip
,size
,extension
Migration for a join table
php yii migrate/create create_news_files_table --fields="news_id:integer:notNull:defaultValue(0),file_id:integer:notNull:defaultValue(0)"
You can add any extra fields, such as
type
to divide files by type orposition
to set sort orderMigration for upload session (since 5.0)
php yii migrate/create create_file_upload_session_table --fields="file_id:integer:notNull:defaultValue(0),created_user_id:integer:notNull:defaultValue(0),target_model_id:integer:defaultValue(0),target_model_class:string:notNull:defaultValue(''),target_model_attribute:string:notNull:defaultValue(''),created_on:datetime"
You can add any extra fields, such as
type
to divide files by type orposition
to set sort order -
Applying Migrations
php yii migrate
-
Declaring a relation
public function getPreviewFile() { return $this ->hasMany(File::className(), ['id' => 'file_id']) ->viaTable('news_files', ['news_id' => 'id']); }
-
Adding upload action
public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'preview-upload' => ['post'] ], ], ]; } public function actions() { return [ 'preview-upload' => [ 'class' => 'rkit\filemanager\actions\UploadAction', 'modelClass' => 'app\models\News', 'attribute' => 'preview', 'inputName' => 'file', ], ]; }
-
Adding behavior
public function behaviors() { return [ [ 'class' => 'rkit\filemanager\behaviors\FileBehavior', 'attributes' => [ 'preview' => [ // any flysystem component for storage 'storage' => 'localFs', // the base URL for files 'baseUrl' => '@web/uploads', // file type (default `image`) 'type' => 'image', // relation name 'relation' => 'previewFile', // save file path in attribute (default `false`) 'saveFilePathInAttribute' => true, // a callback for generating file path // `function(ActiveRecord $file): string` 'templatePath' => function ($file) { $date = new \DateTime(is_object($file->date_create) ? null : $file->date_create); return '/' . $date->format('Ym') . '/' . $file->id . '/' . $file->name; }, // a callback for creating `File` model // `function(string $path, string $name): ActiveRecord` 'createFile' => function ($path, $name) { $file = new File(); $file->title = $name; $file->generateName(pathinfo($name, PATHINFO_EXTENSION)); $file->save(); return $file; }, // a callback for creating `File` model for remote uploads 'createRemoteFile' => function ($info, $name) { $file = new File(); $file->title = $name; $file->created_on = new yii\db\Expression('NOW()'); $file->created_user_id = Yii::$app->user->id; $file->size_bytes = $info->size; $file->generateName($info->url, $name, $this); $file->save(); return $file; }, // core validators 'rules' => [ 'imageSize' => ['minWidth' => 300, 'minHeight' => 300], 'mimeTypes' => ['image/png', 'image/jpg', 'image/jpeg'], 'extensions' => ['jpg', 'jpeg', 'png'], 'maxSize' => 1024 * 1024 * 1, // 1 MB 'maxFiles' => 1, 'tooBig' => Yii::t('app', 'File size must not exceed') . ' 1Mb' ]), // the names[] of presets with callbacks // `function(string $realPath, string $publicPath, string $thumbPath)` 'preset' => [ '220x220' => function ($realPath, $publicPath, $thumbPath) { // you can to use any library for manipulating with files Image::make($realPath . $publicPath) ->fit(220, 220) ->save($realPath . $thumbPath, 100); }, ]), // the names[] of presets or `*` to apply all 'applyPresetAfterUpload' => ['220x220'] ], ] ] ]; }
// any flysystem component for storage
'storage' => 'localFs',
// the base URL for files
'baseUrl' => '@web/uploads',
// file type (default `image`)
'type' => 'image',
// multiple files (default `false`)
'multiple' => false,
// path to template for upload response (the default is an array with id and path of file)
'template' => null,
// a relation name
'relation' => 'previewFile',
// save file path in attribute (default `false`)
'saveFilePathInAttribute' => true,
// save file id in attribute (default `false`)
'saveFileIdInAttribute' => false,
// a callback for generating file path
// `function(ActiveRecord $file): string`
'templatePath' => function ($file) {
$date = new \DateTime(is_object($file->date_create) ? null : $file->date_create);
return '/' . $date->format('Ym') . '/' . $file->id . '/' . $file->name;
},
// a callback for creating `File` model
// `function(string $path, string $name): ActiveRecord`
'createFile' => function ($path, $name) {
$file = new File();
$file->title = $name;
$file->generateName(pathinfo($name, PATHINFO_EXTENSION));
$file->save();
return $file;
},
// a callback for updating `File` model, triggered every time after saving model
// important: return model without saving
// `function(ActiveRecord $file): ActiveRecord`
'updateFile' => function ($file) {
// you can modify attributes (without saving)
return $file;
},
// a callback for filling extra fields, triggered every time after saving model
// `function(ActiveRecord $file, array $fields): array new extra fields`
'extraFields' => function ($file, $fields) {
return [
'type' => 1, if you want to divide files by type
'position' => $positions[$file->id], // if you want to set sort order
];
},
// core validators
'rules' => [
'imageSize' => ['minWidth' => 300, 'minHeight' => 300],
'mimeTypes' => ['image/png', 'image/jpg', 'image/jpeg'],
'extensions' => ['jpg', 'jpeg', 'png'],
'maxSize' => 1024 * 1024 * 1, // 1 MB
'maxFiles' => 1,
'tooBig' => Yii::t('app', 'File size must not exceed') . ' 1Mb'
]),
// the names[] of presets with callbacks
// `function(string $realPath, string $publicPath, string $thumbPath)`
'preset' => [
'220x220' => function ($realPath, $publicPath, $thumbPath) {
// you can to use any library for manipulating with files
Image::make($realPath . $publicPath)
->fit(220, 220)
->save($realPath . $thumbPath, 100);
},
]),
// the names[] of presets or `*` to apply all
'applyPresetAfterUpload' => ['220x220']
To get file
$model->file('preview');
or by relation name
$model->previewFile;
If multiple files
$model->files('gallery');
To get file full path
$model->filePath('preview');
To get file url
$model->fileUrl('gallery');
To create a file manually
$model->createFile('preview', '/path/to/file', 'title');
To create thumbnail and return url
$model->thumbUrl('preview', '200x200');
To create thumbnail and return full path
$model->thumbPath('preview', '200x200');
To get extra fields
$model->fileExtraFields('preview');