1. Go to this page and download the library: Download sem-soft/yii2-filestorage library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
sem-soft / yii2-filestorage example snippets
...
'components' => [
...
'filestorage' => [
'class' => \sem\filestorage\FileStorage::className(),
'storageBaseUrl' => false,
'storagePath' => '@webroot',
'storageDir' => 'upload',
'filemode' => 0775 // Если задан, то после создания файла принудительно будет произведена смена прав на указанные
]
...
],
...
public function actionIndex()
{
$model = new \backend\models\FileForm();
if (Yii::$app->request->isPost) {
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
$file = $model->upload();
}
return $this->render('index', [
'model' => $model
]);
}
public function actionIndex1()
{
$model = new \backend\models\FileForm();
$model->imageFile = new \sem\filestorage\adapters\RemoteFile("https://cs7065.userapi.com/c836722/v836722161/4bff2/mdg7cPZvLrM.jpg");
$file = $model->upload();
return $this->render('index', [
'model' => $model
]);
}
namespace backend\models;
class FileForm extends \yii\base\Model
{
/**
* @var UploadedFile
*/
public $imageFile;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
/**
* @return boolean
*/
public function upload()
{
if ($this->validate()) {
$file = new \sem\filestorage\models\File($this->imageFile,[
'group_code' => 'banners',
'object_id' => '345',
'allowedExtensions' => [
'png',
'jpeg',
'jpg'
]
]);
if ($file->save()) {
return $file;
}
}
return false;
}
}