$endpoint, 'credentials' => [ 'secretId' => $accessKeyId, 'secretKey' => $accessKeySecret ] ]); if (!$cos_client->doesBucketExist($bucket)) { $cos_client->createBucket($bucket); } } catch (\Exception $e) { throw new LogicException($e->getMessage()); } $this->bucket = $bucket; $this->client = $cos_client; return $this; } /** * 上传单个文件,eg:$_FILES['img'] * * @param string $path * @param string $tmpFilePath * @param string $mimeType * @return string * @throws LogicException */ public function uploadSingleFile($path, $tmpFilePath, $mimeType = 'application/octet-stream') { try { $this->client->putObject([ 'Bucket' => $this->bucket, 'Key' => $path, 'Body' => fopen($tmpFilePath, 'rb'), 'ContentType' => $mimeType ]); } catch (\Exception $e) { throw new LogicException($e->getMessage()); } return env('uploadFile.url') . $path; } /** * 上传多文件,eg:$_FILES['imgs'] * * @param array $paths * @param array $tmpPaths * @return array * @throws LogicException */ public function uploadMultiFiles(array $paths, array $tmpPaths) { $signedUrls = []; foreach ($paths as $index => $path) { $signedUrls[$index] = $this->uploadSingleFile($path, $tmpPaths[$index]); } return $signedUrls; } /** * 获取加密的url * * @param $path * @param int $timeout * @return string */ public function getSignedUrl($path, $timeout = 3600) { try { $url = $this->client->signUrl($this->bucket, $path, $timeout); } catch (\Exception $e) { return ''; } return $url; } /** *获取OSS文件 */ public function getOSSFile($fileUrl, $localPath = '') { $fileUrl = str_replace("\\", "/", $fileUrl); $path = parse_url($fileUrl, PHP_URL_PATH); $objectKey = substr($path, 1); try { $config = ['Bucket' => $this->bucket, 'Key' => $objectKey]; if (!empty($localPath)) { $config['SaveAs'] = $localPath; } $content = $this->client->getObject($config); } catch (\Exception $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return ""; } $content = base64_encode($content); return $content; } /** *删除文件 * */ public function deleteOSSFile($fileUrl) { $url = substr($fileUrl, strlen("https://pgevasys.oss-cn-shenzhen.aliyuncs.com")); $url = str_replace("\\", "/", $url); $objectKey = substr($url, 1); try { $this->client->deleteObject($this->bucket, $objectKey); } catch (\Exception $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return false; } return true; } }