manghe/app/admin/controller/Upload2.php
2025-03-21 18:43:39 +08:00

87 lines
2.7 KiB
PHP

<?php
namespace app\admin\controller;
use app\common\server\Upload as uploadss;
use \think\facade\Db;
use \OSS\Core\OssException;
use \OSS\OssClient;
class Upload extends Base
{
/**
* 上传图片
*/
public function picture()
{
// 获取表单上传文件
$files = request()->file();
try {
validate(['image' => 'filesize:10240|fileExt:jpg|image:200,200,jpg'])
->check($files);
$savename = [];
foreach ($files as $file) {
$savename = \think\facade\Filesystem::disk('public')->putFile('topic', $file);
$hash = $file->hash('sha1');
}
} catch (\think\exception\ValidateException $e) {
return $this->renderError($e->getMessage());
}
$savename = '/storage/' . $savename;
$savename = str_replace('\\', '/', $savename);
$pic = Db::name('picture')->where('token', $hash)->find();
if ($pic) {
$return['id'] = $pic['id'];
$return['path'] = imageUrl($pic['imgurl']);
$return['imgurl'] = $pic['imgurl'];
unlink('.' . $savename);
return $this->renderSuccess('上传成功', $return);
}
//判断是否开始阿里云存储
$config = getConfig('uploads');
if ($config['type'] == 2) {
$oss_path = $hash . '.jpg';
$path = $this->aliyunupload($oss_path, '.' . $savename);
unlink('.' . $savename);
$savename = $path;
}
//新增数据
$save_data['imgurl'] = $savename;
$save_data['token'] = $hash;
$save_data['addtime'] = time();
$save_data['status'] = 1;
$resultId = Db::name('picture')->insertGetId($save_data);
if ($resultId) {
$return['id'] = $resultId;
$return['path'] = imageUrl($savename);
$return['imgurl'] = $savename;
return $this->renderSuccess('上传成功', $return);
} else {
return $this->renderError('上传失败');
}
}
//图片上传云存储(阿里云)
public function aliyunupload($filename, $file_path)
{
// $upload = new Uploadss;
// $data = $upload->uploadFile($filename, $file_path);
require_once '../extend/oss/autoload.php';
$config = getConfig('uploads');
$accessKeyId = $config['AccessKeyId'];
$accessKeySecret = $config['AccessKeySecret'];
$endpoint = $config['url'];
$bucket = $config['Bucket'];
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$data = $ossClient->uploadFile($bucket, $filename, $file_path);
dd($data);
return $data;
}
}