<?php
function C($key) {
$array = [
'OSS_ALIYUN' => [
'accessKeyId' => 'accessKeyId','accessKeySecret' => 'accessKeySecret','endpoint' => 'endpoint','bucket' => 'bucket','static' => 'wstatic.apizl.com','path' => '',]
];
return $array[$key];
}
/**
* oss 阿里云
* @author chenran <apiziliao@gmail.com>
*/
class oss {
public $ossClient = null;
public $msg = '';
public function __construct() {
$this->init();
}
/**
* 初始化oss
* @author apizl <apiziliao@gmail.com>
*/
public function init() {
require_once dirname(__FILE__) . '/oss/autoload.php';
$oss = C('OSS_ALIYUN');
$accessKeyId = $oss['accessKeyId'];
$accessKeySecret = $oss['accessKeySecret'];
$endpoint = $oss['endpoint'];
try {
$ossClient = new OSSOssClient($accessKeyId,$accessKeySecret,$endpoint);
} catch (OssException $e) {
$this->msg = $e;
}
$this->ossClient = $ossClient;
}
/**
* 上传指定的本地文件内容
*
* @param string $filePath 路径
* @param string $bucket 存储空间名称
* @return null
*/
public function uploadFile($filePath,$bucket = '') {
if (empty($this->ossClient)) {
$this->init();
}
if (empty($bucket)) {
$bucket = C('OSS_ALIYUN')['bucket'];
}
if (strstr($filePath,$_SERVER['DOCUMENT_ROOT'])) {
$object = str_replace($_SERVER['DOCUMENT_ROOT'],'',$filePath);
$object = substr($object,1);
}
if (strstr($filePath,'./')) {
$object = substr($filePath,2); //oss上服务器位置
}
//$filePath 服务器本地 地址
// $filePath = $_SERVER['DOCUMENT_ROOT'] . "/test.txt";
try {
$this->ossClient->uploadFile($bucket,$object,$filePath);
} catch (OssException $e) {
$this->msg = $e->getMessage();
ThinkLog::write('OSS-uploadFile:' . $e->getMessage());
return false;
}
return true;
}
/**
* 删除object
*
* @param string $filename 文件路径
* @return null
*/
public function deleteObject($filename,$bucket = '') {
if (empty($this->ossClient)) {
$this->init();
}
if (empty($bucket)) {
$bucket = C('OSS_ALIYUN')['bucket'];
}
if (substr($filename,1) == '/') {
$filename = substr($filename,1);
}
$object = $filename;
try {
$this->ossClient->deleteObject($bucket,$object);
} catch (OssException $e) {
return false;
}
return true;
}
}
|