yiiext / file-upload-action
文件上传操作
dev-master
2015-03-07 16:00 UTC
This package is auto-updated.
Last update: 2024-09-13 10:18:53 UTC
README
使用方法
// add action to controller public function actions() { return array( // ... 'upload'=>array( 'class' => 'ext.yiiext.actions.fileUpload.EFileUploadAction', // The data model which contains file attribute with validation rules. 'model' => null, // The model attribute. 'attribute' => null, // The input field name. This must be resolve from model and attribute. 'name' => 'upload-file', // Try create directory if not exists. Defaults to false. 'createDirectory' => false, // Which means the widest possible access. 'createDirectoryMode' => 0644, // Which create directories recursive. 'createDirectoryRecursive' => false, // The rule for generate filename. // i.e. 'filenameRule' => 'md5($file->name) . "." . $file->extensionName', 'filenameRule' => null, // The filename. If not set will be copied original filename. 'filename' => null, // The directory where save files. 'path' => null, 'onBeforeUpload' => function ($event) { // Change default path via event. $event->sender->path=Yii::getPathOfAlias('webroot') . '/files'; }, 'onBeforeSave' => function ($event) { // Add error and cancel uploading. $event->sender->addError(Yii::t('yiiext', 'Process stopped!')); $event->isValid = false; }, 'onAfterSave' => function($event) { // i.e. make thumb for uploaded image. } 'onAfterUpload' => function ($event) { if($event->sender->hasErrors()) { // Show error if exists. echo implode(', ', $event->sender->getErrors()); } else { // Return url. echo str_replace(Yii::getPathOfAlias('webroot'), '', $event->sender->path) . '/' . $event->sender->filename; } // Stop application. exit; } ), // ... ); }
事件
操作包含4个事件,按以下顺序运行
- onBeforeUpload - 此事件主要用于更改操作默认设置:保存路径、文件名等。
- onBeforeSave - 用于更详细地验证下载的文件,可以通过模型实现。此事件可以通过设置
$event->isValid = false
来取消以保存文件 - onAfterSave - 这是一个设计用来操作已保存文件的的事件。
- onAfterUpload - 在此事件中,邀请检查加载、保存或未保存。并显示错误。