闲话不唠 直接上代码
使用 put方式的js_web上传方式 使用的基本是demo里的东西,在官方也有着地址 https://github.com/tencentyun/cos-js-sdk-v5/tree/master/demo 这里只要讲下配置
以下是php代码
<?php
namespace Home\Controller;
use Think\Controller;
//use com\unionpay\acp\sdk\AcpService;
class IndexController extends Controller
{
// 配置参数
public $config = array(
'Url' => 'https://sts.api.qcloud.com/v2/index.php',
'Domain' => 'sts.api.qcloud.com',
'Proxy' => '',
'SecretId' => 'AKIDV5Yw9GCwVs481jB7asywi2CB3mNrtIEy', // 固定密钥
'SecretKey' => 'gCXgeSFxUpywwmQs8C4lGZgdPzObeVBf', // 固定密钥
'Bucket' => 'dsy-1252917505',
'Region' => 'ap-beijing',
'AllowPrefix' => '*', // 这里改成允许的路径前缀,这里可以根据自己网站的用户登录态判断允许上传的目录,例子:* 或者 a/* 或者 a.jpg
);
public function __initialize($config){
// // 缓存临时密钥
// if (!isset($_SESSION['tempKeysCache'])) {
// $_SESSION['tempKeysCache'] = array(
// 'policyStr' => '',
// 'expiredTime' => 0
// );
// }
// $config = $this->config;
}
public function index()
{
$this->display();
}
public function getSign(){
// 获取前端过来的参数
$method = isset($_GET['method']) ? $_GET['method'] : 'get';
$pathname = isset($_GET['pathname']) ? $_GET['pathname'] : '/';
// 获取临时密钥,计算签名
$tempKeys = $this->getTempKeys();
if ($tempKeys && isset($tempKeys['credentials'])) {
$data = array(
'Authorization' => $this->getAuthorization($tempKeys, $method, $pathname),
'XCosSecurityToken' => $tempKeys['credentials']['sessionToken'],
);
} else {
$data = array('error'=> $tempKeys);
}
// 返回数据给前端
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: http://127.0.0.1'); // 这里修改允许跨域访问的网站
header('Access-Control-Allow-Headers: origin,accept,content-type');
echo json_encode($data);
}
// 获取临时密钥
public function getTempKeys() {
// global $config;
// 判断是否修改了 AllowPrefix
if ($this->config['AllowPrefix'] === '_ALLOW_DIR_/*') {
return array('error'=> '请修改 AllowPrefix 配置项,指定允许上传的路径前缀');
}