accessKeyId = config('aliyun.accessKeyId'); $this->accessKeySecret = config('aliyun.accessKeySecret'); $this->endpoint = config('aliyun.endpoint'); // 存储空间名称 $this->bucket = config('aliyun.ossBucket'); } /** * @desc 添加文件 * @param $filePath 上传的文件 * @param $savePath 保存到oss的路径 */ public function uploadFile($filePath, $savePath) { try { $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint); $ossClient->uploadFile($this->bucket, $savePath, $filePath); } catch (OssException $e) { return [false, $e->getMessage()]; } return [true, '']; } /** * @desc 删除文件 * @param deletePath oss的路径 */ public function deleteFile($deletePath) { try { $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint); $ossClient->deleteObject($this->bucket, $deletePath); } catch (OssException $e) { return [false, $e->getMessage()]; } return [true, '']; } /** * @desc 下载文件 * @param string $downLoadFile 下载文件地址 * @param string $saveFile 保存地址 */ public function downLoadFile($downLoadFile, $saveFile) { $localfile = $saveFile; $options = array( OssClient::OSS_FILE_DOWNLOAD => $localfile ); try { $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint); $ossClient->getObject($this->bucket, $downLoadFile, $options); } catch (OssException $e) { return [false, 'msg' => $e->getMessage()]; } return [true, '']; } //生成临时文件 public function getTemporaryUrl($objectKey) { $timeStamp = time(); // 定义本地文件日志路径 $localFilePath = storage_path('app/public/oss_file/' . md5($objectKey) . '.txt'); $directoryPath = dirname($localFilePath); // 检查目录是否存在,如果不存在则创建 if (! is_dir($directoryPath)) { // 设置目录权限,可以根据需要更改 $mode = 0777; // 使用递归选项创建目录 if (!mkdir($directoryPath, $mode, true)) return [false, '目录创建失败']; } $url = ""; if(! file_exists($localFilePath)){ $url = $this->createUrl($objectKey); $set = [ 'url' => $url, 'timestamp' => $timeStamp + 3500, ]; file_put_contents($localFilePath, json_encode($set)); }else{ $content = file_get_contents($localFilePath); $content = json_decode($content,true); if($content['timestamp'] < $timeStamp){ $url = $this->createUrl($objectKey); $set = [ 'url' => $url, 'timestamp' => $timeStamp + 3500, ]; file_put_contents($localFilePath, json_encode($set)); }else{ $url = $content['url']; } } return [true, $url]; } public function createUrl($objectKey, $expiration = 3600){ // 初始化OSS客户端 $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint); // 生成临时链接 $url = $ossClient->signUrl( $this->bucket, $objectKey, $expiration, 'GET' // 可选,指定HTTP方法,默认为 GET ); return $url; } }