opus-online / yii2-file
此包最新版本(v2.0.0)没有可用的许可证信息。
为 Yii2 项目和模块提供的文件系统辅助工具
v2.0.0
2018-07-06 08:22 UTC
Requires
- yiisoft/yii2: >=2.0.13
Requires (Dev)
- phpunit/phpunit: 4.2.*
This package is not auto-updated.
Last update: 2022-10-08 02:41:25 UTC
README
使用方法
文件上传器
要使用 UploadHandler 上传文件,必须使用 ActiveForm。要验证文件输入,必须在与 ActiveForm 一起使用的模型中指定验证规则。如果没有分配文件属性的验证器,则文件不会被验证。如果有多个验证器分配,则执行所有验证器。
以下代码示例演示了如何使用 UploadHandler 与 ActiveForm,以及如何将验证错误传回 ActiveForm
use opus\file\uploader\UploadHandler; /** @var User $user */ $user = $this->getUser(); /** @var Model $this */ try { $fileUpload = new UploadHandler($profileImage->getImageLocationPath(), $this, 'photo'); $uploadedFileNames = $fileUpload->handleUploadedFiles(); foreach ($uploadedFileNames as $fileName) { $user->setAttribute('photo_file_name', $fileName); break; } $user->saveSafe(['photo_file_name']); } catch (InvalidFileUploadException $e) { // now form model will receive the error and assign it to its attribute // you can now throw exception again to catch it in controller level $this->addError('photo', $e->getMessage()); }
如果您在存储文件之前想对文件名进行哈希处理,可以将回调传递给 handleUploadedFiles
$hashFileNamesCallback = function($filename, $fileExtension) { return sprintf('%s.%s', md5($filename), $fileExtension); }; $fileName = $fileUpload->handleUploadedFiles($hashFileNamesCallback)->getUploadedFileNames();
运行测试
运行 composer install
然后在项目根目录中
./vendor/bin/phpunit
变更日志
1.0 - 初始提交