kodia912 / yii2-file-upload
Yii2 文件上传
Requires
- php: >=5.4.0
- yiisoft/yii2-imagine: *
This package is auto-updated.
Last update: 2024-09-27 22:43:13 UTC
README
在分支中修复了错误
PHP 7.2 Cannot use yii\base\Object as Object because 'Object' is a special class name
安装
最方便的安装方法是使用 composer.
或者运行
php composer.phar require --prefer-dist mihaildev/yii2-file-upload "*"
或者添加
"mihaildev/yii2-file-upload": "*"
到您 composer.json 文件中的 require
部分。
为模型配置 Behavior
public function behaviors() { return [ 'file-upload' => [ 'class' => FileUploadBehavior::className(), /* 'replacePairs' => [ '<modelId>' => 'id',// данный набор установлен по умолчанию ], */ 'attributes' => [ 'file' =>[ //'handler' => FileUploadBehavior::HANDLER_FILE, // установлен по умолчанию 'path' => '@webroot/files/<modelId>/<fileName>.<fileExtension>', 'url' => '@web/files/<modelId>/<fileName>.<fileExtension>', ], 'ava' => [ 'handler' => FileUploadBehavior::HANDLER_IMAGE, 'path' => '@webroot/files/avatar/<modelId>/origin.<fileExtension>', 'url' => '@web/files/avatar/<modelId>/origin.<fileExtension>', 'imagine' => function($filename){ return Image::aligning($filename, 800, 800); }, 'saveOptions'=> ['quality' => 90], 'thumbs' => [ 'icon' => [ 'path' => '@webroot/files/avatar/<modelId>/icon.<fileExtension>', 'url' => '@web/files/avatar/<modelId>/icon.<fileExtension>', 'imagine' => function($filename){ return Image::thumbnail($filename, 50, 50);}, 'saveOptions'=> ['quality' => 70], ], 'preview' => [ 'path' => '@webroot/files/avatar/<modelId>/preview.<fileExtension>', 'url' => '@web/files/avatar/<modelId>/preview.<fileExtension>', 'imagine' => function($filename){ return Image::thumbnail($filename, 200, 200);}, 'saveOptions'=> ['quality' => 90], ] ] ] ] ], ]; }
注意!!! 属性必须存储在数据库中!
图像处理通过以下库进行: https://github.com/yiisoft/yii2-imagine
函数 Image::aligning 不包含在标准库中,这里我使用自己的库 https://github.com/MihailDev/yii2-imagine
在模型中获取路径,请使用函数 $this->getUploadedFilePath($attributeName);在模型中获取链接,请使用函数 $this->getUploadedFileUrl($attributeName);
对于图像:$this->getUploadedFilePath($attributeName); - 获取主图像的路径 $this->getUploadedFilePath($attributeName, $thumbId); - 获取副图像的路径
$this->getUploadedFileUrl($attributeName); - 获取主图像的链接 $this->getUploadedFileUrl($attributeName, $thumbId); - 获取副图像的链接
以下是基于上述设置的示例
$this->getUploadedFilePath('file'); $this->getUploadedFileUrl('file');
$this->getUploadedFilePath('ava'); $this->getUploadedFileUrl('ava');
$this->getUploadedFilePath('ava', 'icon'); $this->getUploadedFileUrl('ava', 'icon');
$this->getUploadedFilePath('ava', 'preview'); $this->getUploadedFileUrl('ava', 'preview');
配置和使用小部件
文件
<?= $form->field($model, 'file')->widget(\mihaildev\fileupload\FileUploadWidget::className(),[ 'fileUrl' => $model->getUploadedFileUrl('file'), 'fileName' => 'Скачать' ] ) ?>
图像
<?= $form->field($model, 'ava')->widget(\mihaildev\fileupload\ImageUploadWidget::className(),[ 'imageOptions' => ['width' => '200'], 'imageUrl' => $model->getUploadedFileUrl('ava', 'preview') ] ) ?>