// +---------------------------------------------------------------------- declare (strict_types = 1); namespace app\common\library\storage\engine; use app\common\library\storage\FileValidate; use OSS\OssClient; use OSS\Core\OssException; use think\facade\Env; /** * 阿里云存储引擎 (OSS) * Class Aliyun * @package app\common\library\storage\engine */ class Aliyun extends Basics { /** * 执行上传 * @return bool|mixed */ public function upload() { if (!$this->validate()) { return false; } try { $ossClient = new OssClient( $this->config['access_key_id'], $this->config['access_key_secret'], $this->config['domain'], true ); $result = $ossClient->uploadFile( $this->config['bucket'], $this->getSaveFileInfo()['file_path'], $this->getRealPath() ); } catch (OssException $e) { $this->error = $e->getMessage(); return false; } return true; } /** * 删除文件 * @param string $fileName * @return bool|mixed */ public function delete(string $fileName) { try { $ossClient = new OssClient( $this->config['access_key_id'], $this->config['access_key_secret'], $this->config['domain'], true ); $ossClient->deleteObject($this->config['bucket'], $fileName); } catch (OssException $e) { $this->error = $e->getMessage(); return false; } return true; } /** * 下载文件 * @param $object * @return false|string */ public function download($object){ // 下载Object到本地文件examplefile.txt,并保存到指定的本地路径中(D:\\localpath)。如果指定的本地文件存在会覆盖,不存在则新建。 // 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。 $exts = explode('.',$object); $localfile = runtime_root_path().mt_rand(10000000,99999999).'.'.$exts[1]; $options = array( OssClient::OSS_FILE_DOWNLOAD => $localfile ); // 使用try catch捕获异常。如果捕获到异常,则说明下载失败;如果没有捕获到异常,则说明下载成功。 try{ $ossClient = new OssClient( $this->config['access_key_id'], $this->config['access_key_secret'], Env::get('CHEF.SSO_END_POINT') ); $ossClient->getObject($this->config['bucket'], $object, $options); } catch(OssException $e) { //printf(__FUNCTION__ . ": FAILED\n"); //printf($e->getMessage() . "\n"); log_record($e->getMessage()); return false; } return $localfile; } /** * 验证上传的文件 * @return bool */ private function validate() { $FileValidate = new FileValidate; if (!$FileValidate->check([$this->validateRuleScene => $this->file])) { $this->error = $FileValidate->getError(); return false; } return true; } }