<?php
final class oss_config {
const OSS_ACCESS_ID = '';
const OSS_ACCESS_KEY = '';
const OSS_ENDPOINT = '';
const OSS_BUCKET = '';
}2、新建oss类,实现单例<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2016年12月3日
* Time: 22:04
*/
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
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2016年11月5日
* Time: 22:43
*/
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();
}
}
}
ThinkPHP 是一个免费开源的,快速、简单的面向对象的 轻量级PHP开发框架 ,创立于2006年初,遵循Apache2开源协议发布,是为了敏捷WEB应用开发和简化企业应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。并且拥有众多的原创功能和特性,在社区团队的积极参与下,在易用性、扩展性和性能方面不断优化和改进,已经成长为国内最领先和最具影响力的WEB应用开发框架,众多的典型案例确保可以稳定用于商业以及门户级的开发。