使用thinkphp5实现oss文件上传
使用thinkphp5实现oss文件上传,实现静态资源与网站分离。本功能使用到了阿里云oss的php接口,请先下载安装aliyun-oss-php-sdk到项目扩展文件夹中,具体请参照oss的接口文档。
1、配置文件oss.php
<?php
final class oss_config {
const OSS_ACCESS_ID = '';
const OSS_ACCESS_KEY = '';
const OSS_ENDPOINT = '';
const OSS_BUCKET = '';
}
复制代码
2、新建oss类,实现单例
<?php
namespace base;
use OSS\OssClient;
class Oss {
const accessKeyId = \oss_config::OSS_ACCESS_ID;
const accessKeySecret = \oss_config::OSS_ACCESS_KEY;
const endpoint = \oss_config::OSS_ENDPOINT;
const bucket = \oss_config::OSS_BUCKET;
private static $_instance;
/**
* 构造函数
* Oss constructor.
*/
private function __construct() {
}
/**
* 克隆
*/
private function __clone() {
}
/**
* 获取一个OssClient实例
* @return null|OssClient
*/
public static function getInstance() {
if (!(self::$_instance instanceof OssClient)) {
try {
self::$_instance = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, false);
} catch (OssException $e) {
printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
printf($e->getMessage() . "\n");
return null;
}
}
return self::$_instance;
}
/**
* 获取bucket
* @return string
*/
public static function getBucketName()
{
return self::bucket;
}
}
复制代码
3、html模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" name="fileinfo" action="/index/test/index">
<table>
<tr>
<td>上传文件:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="上传"></td>
</tr>
</table>
</form>
</body>
</html>
复制代码
4、上传服务器端
<?php
namespace osc\index\controller;
use osc\common\controller\HomeBase;
use base\Oss;
class Test extends HomeBase {
public function index() {
if (request()->isPost()) {
try {
$file = request()->file('image');
if (empty($file)) {
die('请选择上传的文件');
}
$allow_max_size = 2 * pow(1024, 2);
$allow_upload_ext = ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'wbmp'];
$path = ROOT_PATH . 'public' . DS . 'uploads';
$info = $file->validate(['size' => $allow_max_size, 'ext' => $allow_upload_ext])->move($path);
if (!$info) {
var_dump($file->getError());
die();
}
$fileName = 'uploads/' . $info->getSaveName();
$ossClient = Oss::getInstance();
$bucket = Oss::getBucketName();
$ossClient->uploadFile($bucket, $fileName, $info->getPathname());
} catch (OssException $e) {
return $e->getMessage();
}
} else {
return $this->fetch();
}
}
}