Browse Source

feat: 新增upload文件上传

wechat_public_accounts
iron 5 years ago
parent
commit
92bcd92f60
  1. 1
      .gitignore
  2. 3
      common/config/main.php
  3. 9
      kcadmin/controllers/CategoryController.php
  4. 3
      kcadmin/controllers/SiteController.php
  5. 2
      kcadmin/views/category/index.php
  6. 176
      vendor/iron/actions/UploadAction.php

1
.gitignore

@ -36,3 +36,4 @@ phpunit.phar
/.vagrant /.vagrant
vendor.zip vendor.zip
/vagrant /vagrant
/kcadmin/web/uploads

3
common/config/main.php

@ -4,7 +4,8 @@ return [
'aliases' => [ 'aliases' => [
'@bower' => '@vendor/bower-asset', '@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset', '@npm' => '@vendor/npm-asset',
'@blobt' => '@vendor/blobt'
'@blobt' => '@vendor/blobt',
'@iron' => '@vendor/iron'
], ],
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor', 'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'timeZone' => 'Asia/Shanghai', 'timeZone' => 'Asia/Shanghai',

9
kcadmin/controllers/CategoryController.php

@ -13,7 +13,7 @@ use yii\filters\VerbFilter;
* CategoryController implements the CRUD actions for Category model. * CategoryController implements the CRUD actions for Category model.
*/ */
class CategoryController extends Controller { class CategoryController extends Controller {
public $enableCsrfValidation = false;
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
@ -28,6 +28,13 @@ class CategoryController extends Controller {
]; ];
} }
public function actions() {
return [
'test'=>[
'class'=>'iron\actions\UploadAction',
]
];
}
/** /**
* Lists all Category models. * Lists all Category models.
* @return mixed * @return mixed

3
kcadmin/controllers/SiteController.php

@ -50,6 +50,9 @@ class SiteController extends Controller {
'error' => [ 'error' => [
'class' => 'yii\web\ErrorAction', 'class' => 'yii\web\ErrorAction',
], ],
'upload'=>[
'class'=>'iron\actions\UploadAction',
]
]; ];
} }

2
kcadmin/views/category/index.php

@ -65,7 +65,7 @@ $this->params['breadcrumbs'][] = $this->title;
], ],
[ [
'class' => 'blobt\grid\ActionColumn', 'class' => 'blobt\grid\ActionColumn',
'align' => 'center'
'align' => 'center',
], ],
], ],
]); ]);

176
vendor/iron/actions/UploadAction.php

@ -0,0 +1,176 @@
<?php
/*
* The MIT License
*
* Copyright 2019 Blobt.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace iron\actions;
use yii\base\Action;
use Yii;
use yii\base\Exception;
use yii\web\Response;
use yii\web\UploadedFile;
/***
* @author iron <weiriron@gmail.com>
* @created Sep 11, 2019
*/
class UploadAction extends Action
{
/**
* 常量:表单数据类型
*/
const DATA_TYPE_FORM = 1;
/**
* 常量: 二进制数据类型
*/
const DATA_TYPE_BINARY = 2;
/**
* @var integer 限制的最大尺寸
*/
public $maxSize;
/**
* @var array 允许的文件类型(扩展名)
*/
public $allowType;
/**
* @var string 文件保存路径
*/
public $path;
/**
* @var string 数据类型
*/
public $dataType;
/**
* @var bool 是否随机文件名(默认为随机,推荐为随机避免中文文件名导致的问题)
*/
public $randName = true;
/**
* @var integer 默认单次最大上传数量(1-20
*/
public $maxCount;
public function init()
{
if ($this->maxSize === null) {
$this->maxSize = 2048;//默认最大尺寸为2M
}
if ($this->allowType === null) {
$this->allowType = ['*'];//默认允许任何图片类型
}
if ($this->maxCount === null) {
$this->maxCount = 5;//默认单次最大上传数量为5
}
if ($this->dataType === null) {
$this->dataType = self::DATA_TYPE_FORM;//默认上传数据类型为表单数据
}
}
public function run()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$data = [];
d(Yii::$app->request->post());exit;
if ($this->dataType == self::DATA_TYPE_FORM) {
$files = UploadedFile::getInstancesByName('files');
} else {
//TODO 非表单类型的文件上传
$files = [];
}
try {
foreach ($files as $file) {
$this->checkType($file->extension);
$this->checkSize($file->size);
$savePath = $this->getSavePath();
$fileName = $this->getFileName($file->baseName);
$filePath = "$savePath/$fileName.{$file->extension}";
$file->saveAs($filePath);
$data[] = ["uploads/$this->path/$fileName.{$file->extension}"];
}
return ['status' => true, 'paths' => $data];
} catch (\Exception $e) {
return ['status' => false, 'info' => $e->getMessage()];
}
}
/**
* 检查文件类型是否允许上传
* @param $extension 文件扩展名
* @return bool
* @throws Exception
*/
protected function checkType($extension)
{
if (in_array('*', $this->allowType)) {
return true;
}
if (!in_array($extension, $this->allowType)) {
throw new Exception("类型【{$extension}】不被允许,请在配置项中添加该类型");
}
}
/**
* 检查文件尺寸是否超过最大允许上传尺寸
* @param $size 文件尺寸
* @throws Exception
*/
protected function checkSize($size)
{
if ($size/1024 > $this->maxSize) {
throw new Exception("文件大于允许的最大尺寸【{$this->maxSize}】,请修改配置或压缩文件");
}
}
/**
* 获取文件保存路径并创建文件夹
* @return string 文件保存的完成路径
*/
protected function getSavePath()
{
$dirs = explode('/', $this->path);
$savePath = Yii::getAlias('@app').'/web/uploads';
if (!is_dir($savePath)) {
mkdir($savePath, 755);
}
foreach ($dirs as $dir) {
$savePath .= "/{$dir}";
if (!is_dir($savePath)) {
mkdir($savePath, 755);
}
}
return $savePath;
}
/**
* 利用时间戳加随机数构建新文件名
* @param $originName 源文件名
* @return string
*/
//TODO 利用原文件名生成新文件名
protected function getFileName($originName)
{
return time() . rand(0, 9999);
}
}
Loading…
Cancel
Save