Files
premium/plugin/meditor/controller/Common.php
T
2025-05-18 07:29:01 +00:00

102 lines
4.2 KiB
PHP

<?php
/**
* mdeditor上传图片接口
*/
namespace plugin\meditor\controller;
use app\service\ConfServiceFacade;
use laytp\library\UploadDomain;
use plugin\ali_oss\service\Oss;
use plugin\qiniu_kodo\service\Kodo;
use laytp\controller\Backend;
use think\facade\Env;
use think\facade\Filesystem;
class Common extends Backend
{
protected $noNeedLogin = ['*'];
//上传接口
public function upload()
{
try {
$uploadType = $this->request->param('upload_type', 'local');
$file = $this->request->file('editormd-image-file'); // 获取上传的文件
if (!$file) {
return $this->error('上传失败,请选择需要上传的文件');
}
$fileExt = strtolower($file->getOriginalExtension());
$uploadDomain = new UploadDomain();
if (!$uploadDomain->check($file->getOriginalName(), $file->getSize(), $fileExt, $file->getMime())) {
return $this->error($uploadDomain->getError());
}
$saveName = date("Ymd") . "/" . md5(uniqid(mt_rand())) . ".{$fileExt}";
/**
* 不能以斜杆开头
* - 因为OSS存储时,不允许以/开头
*/
$uploadDir = $this->request->param('dir');
$object = $uploadDir ? $uploadDir . '/' . $saveName : $saveName;//设置了上传目录的上传文件名
$inputValue = "";
//上传至七牛云
if ($uploadType == 'qiniu-kodo') {
if(ConfServiceFacade::get('qiniuKodo.conf.switch') != 1){
return $this->error('未开启七牛云KODO存储,请到七牛云KODO配置中开启');
}
$kodoConf = [
'accessKey' => ConfServiceFacade::get('qiniuKodo.conf.accessKey'),
'secretKey' => ConfServiceFacade::get('qiniuKodo.conf.secretKey'),
'bucket' => ConfServiceFacade::get('qiniuKodo.conf.bucket'),
'domain' => ConfServiceFacade::get('qiniuKodo.conf.domain'),
];
$kodo = Kodo::instance();
$kodoRes = $kodo->upload($file->getPathname(), $object, $kodoConf);
if ($kodoRes) {
$inputValue = $kodoRes;
} else {
return $this->error($kodo->getError());
}
}
//上传至阿里云
if ($uploadType == 'ali-oss') {
if(ConfServiceFacade::get('system.aliOss.switch') != 1){
return $this->error('未开启阿里云OSS存储,请到阿里云OSS配置中开启');
}
$ossConf = [
'accessKeyID' => ConfServiceFacade::get('aliOss.conf.accessKeyID'),
'accessKeySecret' => ConfServiceFacade::get('aliOss.conf.accessKeySecret'),
'bucket' => ConfServiceFacade::get('aliOss.conf.bucket'),
'endpoint' => ConfServiceFacade::get('aliOss.conf.endpoint'),
'domain' => ConfServiceFacade::get('aliOss.conf.domain'),
];
$oss = Oss::instance();
$ossUploadRes = $oss->upload($file->getPathname(), $object, $ossConf);
if ($ossUploadRes) {
$inputValue = $ossUploadRes;
} else {
return $this->error($oss->getError());
}
}
//本地上传
if ($uploadType == 'local') {
$uploadDir = ltrim('/', $uploadDir);
$saveName = Filesystem::putFileAs('/' . $uploadDir, $file, '/' . $object);
$staticDomain = Env::get('domain.static');
if ($staticDomain) {
$inputValue = $staticDomain . '/storage/' . $saveName;
} else {
$inputValue = request()->domain() . '/static/storage/' . $saveName;
}
}
return json(['url' => $inputValue, 'success' => 1]);
} catch (\Exception $e) {
return $this->exceptionError($e);
}
}
}