70 lines
2.5 KiB
PHP
70 lines
2.5 KiB
PHP
<?php
|
||
|
||
namespace app\czg\app\controller;
|
||
|
||
use app\common\controller\Frontend;
|
||
use ba\Random;
|
||
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
|
||
use OSS\OssClient;
|
||
use OSS\Core\OssException;
|
||
use think\facade\Db;
|
||
use support\Log;
|
||
|
||
class AliossController extends Frontend
|
||
{
|
||
|
||
|
||
protected array $noNeedLogin = ['*'];
|
||
public function upload()
|
||
{
|
||
$file = request()->file('file');
|
||
if(empty($file)) {
|
||
$this->error('参数不能为空');
|
||
}
|
||
$commoninfo = Db::connect(config('think-orm.search_library'));
|
||
$endpoint = $commoninfo->name('common_info')->where(['type' => 68])->find()['value'];
|
||
$accessKeyId = $commoninfo->name('common_info')->where(['type' => 69])->find()['value'];
|
||
$secretAccessKey = $commoninfo->name('common_info')->where(['type' => 70])->find()['value'];
|
||
$bucket = $commoninfo->name('common_info')->where(['type' => 71])->find()['value'];
|
||
$befor_url = $commoninfo->name('common_info')->where(['type' => 72])->find()['value'];
|
||
|
||
putenv('OSS_ACCESS_KEY_ID=' . $accessKeyId);
|
||
putenv('OSS_ACCESS_KEY_SECRET='. $secretAccessKey);
|
||
$provider = new EnvironmentVariableCredentialsProvider();
|
||
|
||
$object = date('Ymd') . '/' . uniqid() . '.' .$file->getUploadExtension();
|
||
try{
|
||
$config = array(
|
||
"provider" => $provider,
|
||
"endpoint" => $endpoint,
|
||
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V1,
|
||
);
|
||
$ossClient = new OssClient($config);
|
||
// 以二进制模式读取文件内容
|
||
$handle = fopen($file->getRealPath(), 'rb');
|
||
$content = stream_get_contents($handle);
|
||
fclose($handle);
|
||
|
||
// 上传二进制内容,明确指定Content-Type
|
||
$options = [
|
||
OssClient::OSS_CONTENT_LENGTH => strlen($content),
|
||
OssClient::OSS_CONTENT_TYPE => $file->getUploadMimeType(),
|
||
// 禁用字符编码转换
|
||
'Content-Encoding' => 'binary',
|
||
];
|
||
$res = $ossClient->putObject($bucket, $object, $content, $options);
|
||
Log::info('上传文件结果' . json_encode($res));
|
||
if(!empty($res['info'])) {
|
||
return $this->ApiDataReturn(['data' => $befor_url . '/' . $object, 'msg' => 'success', 'code' => 0]);
|
||
}else {
|
||
$this->error('上传失败');
|
||
}
|
||
} catch(OssException $e) {
|
||
$this->error($e->getMessage());
|
||
}
|
||
|
||
|
||
}
|
||
|
||
|
||
} |