Files
xk-api-yii/common/services/UploadService.php

249 lines
8.7 KiB
PHP
Raw Normal View History

2024-09-19 11:32:39 +08:00
<?php
namespace common\services;
use common\helpers\FuncHelper;
use GuzzleHttp\Client;
use OSS\Core\OssException;
use OSS\OssClient;
use yii\base\Exception;
use yii\web\UploadedFile;
class UploadService{
protected $docExt = ['txt', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv', 'pdf', 'md'];
protected $imageExt = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp',];
protected $videoExt = ['mp4', 'ogg', 'm4a',];
protected static $guzzleOptions = ['http_errors' => false];
public function __construct()
{
$this->storage = \Yii::$app->params['upload'];
}
/**
* Get a fresh instance of the Guzzle HTTP client.
*
* @return \GuzzleHttp\Client
*/
protected function getHttpClient()
{
return new Client(self::$guzzleOptions);
}
public function index($name)
{
$file = UploadedFile::getInstanceByName($name);
$this->file = $file;
$this->validateSize();
$this->saveFileFolder = '/uploads/' . date('Ymd');
$this->saveFileName = md5_file($this->file->tempName) . '.' . $this->file->getExtension();
switch($this->storage['type']){
case 'alioss':
$this->saveToAliOss();
break;
default:
$this->saveToLocal();
break;
}
return $this->url;
}
public function validateSize()
{
$supportExt = array_merge($this->docExt, $this->imageExt, $this->videoExt);
if (!in_array($this->file->extension, $supportExt)) {
throw new Exception('不支持的文件类型: ' . $this->file->extension);
}
if (in_array($this->file->extension, $this->imageExt)) {
if ($this->storage['image_limit'] && $this->file->size > $this->storage['image_limit'] * 1024 * 1024) {
throw new Exception('图片大小超出限制,当前大小为: '
. (round($this->file->size / 1024 / 1024, 4)) . 'MB,最大限制为:'
. $this->storage['image_limit'] . 'MB');
}
}
if (in_array($this->file->extension, $this->videoExt)) {
if ($this->storage['video_limit'] && $this->file->size > $this->storage['video_limit'] * 1024 * 1024) {
throw new Exception('视频大小超出限制,当前大小为: '
. (round($this->file->size / 1024 / 1024, 4)) . 'MB,最大限制为:'
. $this->storage['video_limit'] . 'MB');
}
}
}
private function saveToLocal()
{
$saveFile = $this->storage['path'] . $this->saveFileFolder . '/' . $this->saveFileName;
$dir = dirname($saveFile);
FuncHelper::make_dir($dir);
if(move_uploaded_file($this->file->tempName,$saveFile)){
$this->url = $this->storage['url'] . $this->saveFileFolder . '/' . $this->saveFileName;
}else{
throw new Exception('上传图片失败');
}
}
public function saveToAliOss()
{
try {
$config = $this->storage['alioss'];
$isCName = (!empty($config['is_cname']) && $config['is_cname'] == 1) ? true : false;
$client = new OssClient($config['access_key'], $config['secret_key'], $config['domain'], $isCName);
$object = trim($this->saveFileFolder . '/' . $this->saveFileName, '/');
$client->uploadFile($config['bucket'], $object, $this->file->tempName);
if (!$isCName) {
$endpointNameStart = mb_stripos($config['domain'], '://') + 3;
$urlPrefix = mb_substr($config['domain'], 0, $endpointNameStart)
. $config['bucket']
. '.'
. mb_substr($config['domain'], $endpointNameStart);
} else {
$urlPrefix = $config['domain'];
}
$this->url = $urlPrefix . $this->saveFileFolder . '/' . $this->saveFileName;
} catch (OssException $e) {
throw new Exception($e->getMessage());
}
}
public function saveFile($file_path)
{
$this->saveFileFolder = '/uploads/' . date('Ymd');
$this->saveFileName = md5_file($file_path) . '.' . strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
try {
$config = $this->storage['alioss'];
$isCName = (!empty($config['is_cname']) && $config['is_cname'] == 1) ? true : false;
$client = new OssClient($config['access_key'], $config['secret_key'], $config['domain'], $isCName);
$object = trim($this->saveFileFolder . '/' . $this->saveFileName, '/');
$client->uploadFile($config['bucket'], $object,$file_path);
if (!$isCName) {
$endpointNameStart = mb_stripos($config['domain'], '://') + 3;
$urlPrefix = mb_substr($config['domain'], 0, $endpointNameStart)
. $config['bucket']
. '.'
. mb_substr($config['domain'], $endpointNameStart);
} else {
$urlPrefix = $config['domain'];
}
$this->url = $urlPrefix . $this->saveFileFolder . '/' . $this->saveFileName;
unlink($file_path);
return $this->url;
} catch (OssException $e) {
unlink($file_path);
throw new Exception($e->getMessage());
}
}
/**
* 阿里云直传
*/
public function redirectFile($data)
{
$config = $this->storage['alioss'];
$callbackUrl = $data['callbackUrl'];
$dir = $data['dir'];
$key = $config['secret_key'];
$id = $config['access_key'];
$host = $config['domain'];
$callback_param = array(
'callbackUrl' => $callbackUrl,
'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
'callbackBodyType' => "application/x-www-form-urlencoded"
);
$callback_string = json_encode($callback_param);
$base64_callback_body = base64_encode($callback_string);
$now = time();
$expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间将不能访问。
$end = $now + $expire;
$expiration = $this->gmt_iso8601($end);
//最大文件大小.用户可以自己设置
// $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
// $conditions[] = $condition;
// 表示用户上传的数据,必须是以$dir开始不然上传会失败这一步不是必须项只是为了安全起见防止用户通过policy上传到别人的目录。
$start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
$conditions[] = $start;
$arr = array('expiration' => $expiration, 'conditions' => $conditions);
$policy = json_encode($arr);
$base64_policy = base64_encode($policy);
$string_to_sign = $base64_policy;
$signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));
$response = array();
$response['accessid'] = $id;
$response['host'] = $host;
$response['policy'] = $base64_policy;
$response['signature'] = $signature;
$response['expire'] = $end;
$response['callback'] = $base64_callback_body;
$response['dir'] = $dir; // 这个参数是设置用户上传文件时指定的前缀。
$response['savename'] = md5(time().mt_rand(100,999));
return $response;
}
public function gmt_iso8601($time)
{
return str_replace('+00:00', '.000Z', gmdate('c', $time));
}
/**
* 获取直传回调公钥
*/
public function getPublicKey($pubKeyUrlBase64)
{
try {
$pubKeyUrl = base64_decode($pubKeyUrlBase64);
$response = $this->getHttpClient()->get($pubKeyUrl);
$body = $response->getBody();
$buffer = $body->getContents();
return $buffer;
}catch (\Exception $exception){
return "";
}
}
/**
* 处理下返回,域名前缀
*/
public function getBody($body)
{
$config = $this->storage['alioss'];
parse_str($body,$body_arr);
$isCName = (!empty($config['is_cname']) && $config['is_cname'] == 1) ? true : false;
if (!$isCName) {
$endpointNameStart = mb_stripos($config['domain'], '://') + 3;
$urlPrefix = mb_substr($config['domain'], 0, $endpointNameStart)
. $config['bucket']
. '.'
. mb_substr($config['domain'], $endpointNameStart);
} else {
$urlPrefix = $config['domain'];
}
$body_arr['filename'] = $urlPrefix . '/' . $body_arr['filename'];
return $body_arr;
}
}