common/components 路径下新建Upload.php
<?php
namespace common\components;
use yii;
use yii\web\UploadedFile;
use yii\helpers\FileHelper;
class Upload
{
/**
* @param \yii\base\Model $model 实例化模型
* @param string $inputName <input name="$inputName">
* @param array $config 上传文件配置
* @return array
*/
public function upload($model, $inputName, $config = [])
{
// 文件上传路径
$folder = isset($config['uploadPath']) ? '/' . $config['uploadPath'] . '/' : '/';
$path = Yii::getAlias('@uploads') . $folder;
if (FileHelper::createDirectory($path) === true) {
$files = UploadedFile::getInstance($model, $inputName);
if ($files) {
$fileSize = isset($config['fileSize']) ? $config['fileSize'] : 50 * 1024 * 1024; // 默认50M
$allowType = isset($config['allowType']) ? $config['allowType'] : ['jpg', 'jpeg', 'gif', 'png', 'bmp'];
// 扩展名
$ext = $files->getExtension();
if (empty($ext)) {
$ext_tmp = explode('/', $files->type);
$ext = isset($ext_tmp[1]) ? $ext_tmp[1] : '';
}
if (!in_array(strtolower($ext), $allowType)) {
return ['code' => -1, 'msg' => '上传的文件类型不允许', 'data' => []];
}
// 文件大小
if ($files->size > $fileSize) {
return ['code' => -1, 'msg' => '上传的文件大小超过给定值', 'data' => []];
}
// 文件名
$fileName = uniqid() . '.' . $ext;
if ($files->saveAs($path . $fileName)) {
return ['code' => 0, 'msg' => '上传成功', 'data' => $folder . $fileName];
} else {
return ['code' => -1, 'msg' => '文件保存失败', 'data' => []];
}
} else {
return ['code' => -1, 'msg' => '未上传文件', 'data' => []];
}
} else {
return ['code' => -1, 'msg' => '上传路径错误', 'data' => []];
}
}
}
调用第一种方法:
可在common\config/main.php 配置组件
'uploadFile' => [
'class' => 'common\components\Upload',
],
调用
$logo = Yii::$app->uploadFile->uploadImage($model, '/logo/', 'logoFile');
第二种:直接实例化调用
use common\components\Upload;
$upload = new Upload();
$upload->uploadImage($model, '/logo/', 'logoFile');