##文件上传
* 文件上传按钮, 用来替换原生的file input,它只是对native File Input的外观wrapper, 自己还要写如何处理上传文件, noam148/yii2-image-manager内部也是利用的它, 感觉它是一个半成品,仅仅是比原生的样式好一些而已?
~~~
<?php echo \kartik\file\FileInput::widget([
'name' => 'attachments',
'options' => ['multiple' => true],
'pluginOptions' => ['previewFileType' => 'any']
]); ?>
或
<?php echo \kartik\file\FileInput::widget([
'name' => 'imagemanagerFiles[]',
'id' => 'imagemanager-files',
'options' => [
'multiple' => true,
'accept' => 'image/*'
],
'pluginOptions' => [
'uploadUrl' => Url::to(['/manager/upload']),
'allowedFileExtensions' => \Yii::$app->getModule('imagemanager')->allowedFileExtensions,
'uploadAsync' => false,
'showPreview' => false,
'showRemove' => false,
'showUpload' => false,
'showCancel' => false,
'browseClass' => 'btn btn-primary btn-block',
'browseIcon' => '<i class="fa fa-upload"></i> ',
'browseLabel' => 'Upload'
],
'pluginEvents' => [
"filebatchselected" => "function(event, files){ $('.msg-invalid-file-extension').addClass('hide'); $(this).fileinput('upload'); }",
"filebatchuploadsuccess" => "function(event, data, previewId, index) {
imageManagerModule.uploadSuccess(data.jqXHR.responseJSON.imagemanagerFiles);
}",
"fileuploaderror" => "function(event, data) { $('.msg-invalid-file-extension').removeClass('hide'); }",
],
]) ?>
~~~
* 处理动作
~~~
public function actionUpload() {
// 处理多个文件
if (isset($_FILES['imagemanagerFiles']['tmp_name'])) {
foreach ($_FILES['imagemanagerFiles']['tmp_name'] AS $key => $sTempFile) {
$sFileName = $_FILES['imagemanagerFiles']['name'][$key];
$sFileExtension = pathinfo($sFileName, PATHINFO_EXTENSION);
$iErrorCode = $_FILES['imagemanagerFiles']['error'][$key];
if ($iErrorCode == 0) {
//create a file record
$model = new ImageManager();
$model->fileName = str_replace("_", "-", $sFileName);
$model->fileHash = Yii::$app->getSecurity()->generateRandomString(32);
//if file is saved add record
if ($model->save()) {
$sSaveFileName = $model->id . "_" . $model->fileHash . "." . $sFileExtension;
//move_uploaded_file($sTempFile, $sMediaPath."/".$sFileName);
//save with Imagine class
Image::getImagine()->open($sTempFile)->save($sMediaPath . "/" . $sSaveFileName);
}
}
}
}
}
~~~