微信小程序/网站 上传图片到腾讯云COS

COS简介: 腾讯云提供的一种对象存储服务,供开发者存储海量文件的分布式存储服务。可以将自己开发的应用的存储部分全部接入COS的存储桶中,有效减少应用服务器的带宽,请求等。个人也可以通过腾讯云账号免费使用COS6个月,https://cloud.tencent.com/product/cos

整体流程简介: 

1. 前端引入cos的SDK文件

2. 监听上传控件,并在图片加载至网页临时流中发起签名请求

3.后端根据上传的请求方式和路径参数返回签名Authorization和token XCosSecurityToken

4.前端再根据返回的参数和SDK以3的请求方式上传图片。

PHP签名返回流程:

1.在腾讯云的建好存储桶并配置CORS规则https://cloud.tencent.com/document/product/436/11459

2.在平台上拿到Bucket(存储桶),Region(地域),SecretId,SecretKey等参数。

3.使用(SecretId,Timestamp…)参数进行签名通过腾讯云的接口获取临时密钥,返回给前端的token也在临时密钥中

4.根据前端传的(上传请求方式,路径)和临时密钥进行签名(前端上传所使用的)并返回。

一、PHP获取签名部分(tp5)

<?php
// +----------------------------------------------------------------------
// | When work is a pleasure, life is a joy!
// +----------------------------------------------------------------------
// | User: 傅超|  Email:1741108471@qq.com | Time:2018/04/21 17:55
// +----------------------------------------------------------------------
// | TITLE: 小程序接口
// +----------------------------------------------------------------------

namespace app\v1\controller;

use think\Request;
use think\Db;
use app\v1\location\Location;
use think\Cache;
use \app\v1\auth\AccessToken;
use \app\v1\extend\Loginlog;

// 返回数据给前端
header(‘Content-Type: application/json‘);
header(‘Allow-Control-Allow-Origin: *‘);       // 这里修改允许跨域访问的网站
// header(‘Allow-Control-Allow-Origin: http://127.0.0.1‘);       // 这里修改允许跨域访问的网站
//header(‘Allow-Control-Allow-Origin: http://mer.runmoneyin.com‘); // 这里修改允许跨域访问的网站
header(‘Allow-Control-Allow-Headers: origin,accept,content-type‘);


/**
 * Class  Cosauth
 * @title 获取腾讯云cos签名接口
 * @url   http://119.29.10.64/v1/Cosauth
 * @desc  小程序接口包含:获取上传图片签名
 * @version 1.0
 */
class Cosauth extends Base
{
    // 附加方法
    protected $extraActionList = [‘getCosAuth‘, ‘getCosAuth‘];

    // 跳过验证方法
    protected $skipAuthActionList = [‘getCosAuth‘, ‘getCosAuthEsay‘];

    // appid
    //protected $appid = ‘wx4c0e1852239664b4‘;

    // cos配置参数
    protected $config = array(
        ‘Url‘         => ‘https://sts.api.qcloud.com/v2/index.php‘,
        ‘Domain‘      => ‘sts.api.qcloud.com‘,   
        ‘Proxy‘       => ‘‘,
        ‘SecretId‘    => ‘AK********************BLK9nF5dZL‘, // 固定密钥
        ‘SecretKey‘   => ‘jHj5G*********************IUcqJu‘,     // 固定密钥
        ‘Bucket‘      => ‘activity-1255484416‘,               // 存储桶
        ‘Region‘      => ‘ap-guangzhou‘,
        ‘AllowPrefix‘ => ‘*‘, // 这里改成允许的路径前缀,这里可以根据自己网站的用户登录态判断允许上传的目录,例子:* 或者 a/* 或者 a.jpg
    );

    /**
     * @title 获取签名入口
     * http://119.29.10.64/v1/Cosauth/getCosAuth
     */
    public function getCosAuth() {
        // $data[‘say‘] = ‘hello‘;
        // echo json_encode($data);
        // die;

        // 缓存临时密钥
        if (!isset($_SESSION[‘tempKeysCache‘])) {
            $_SESSION[‘tempKeysCache‘] = array(
                ‘policyStr‘ => ‘‘,
                ‘expiredTime‘ => 0
            );
        }

        // 获取前端过来的参数
        // $method = isset($_GET[‘method‘]) ? $_GET[‘method‘] : ‘get‘;
        // $pathname = isset($_GET[‘pathname‘]) ? $_GET[‘pathname‘] : ‘/‘;
        
        $method   = input(‘method‘) ? input(‘method‘) : ‘post‘;
        $pathname = input(‘pathname‘) ? input(‘pathname‘) : ‘/‘;
        $callback = input(‘callback‘) ? input(‘callback‘) : ‘‘;    // 前端跨域的jsonp参数(可忽略)

        // 获取临时密钥,计算签名
        $tempKeys = $this->getTempKeys();

        if ($tempKeys && $tempKeys[‘credentials‘]) {

            // $datas = $this->getAuthorization($tempKeys, $method, $pathname);
            // echo json_encode($datas);
            // die;
            $data = array(
                ‘Authorization‘ => $this->getAuthorization($tempKeys, $method, $pathname),
                ‘XCosSecurityToken‘ => $tempKeys[‘credentials‘][‘sessionToken‘],
            );

        } else {
            $data = array(‘error‘=> $tempKeys);
        }

        //echo $callback . ‘(‘ . json_encode($data) . ‘)‘;     // 通过回调返回给其他域(可忽略)
        echo json_encode($data);     // 正常写法的返回
        die;
    }


    // json 转 query string
    public function json2str($obj, $notEncode = false) {
        ksort($obj);
        $arr = array();
        foreach ($obj as $key => $val) {
            !$notEncode && ($val = urlencode($val));
            array_push($arr, $key . ‘=‘ . $val);
        }
        return join(‘&‘, $arr);
    }

    // 计算临时密钥用的签名
    public function getSignature($opt, $key, $method) {
        //global $config;
        $formatString = $method . $this->config[‘Domain‘] . ‘/v2/index.php?‘ . $this->json2str($opt, 1);
        $sign = hash_hmac(‘sha1‘, $formatString, $key);
        $sign = base64_encode(hex2bin($sign));
        return $sign;
    }

    // 获取临时密钥
    public function getTempKeys() {

        //global $config;

        // 判断是否修改了 AllowPrefix
        if ($this->config[‘AllowPrefix‘] === ‘_ALLOW_DIR_/*‘) {
            return array(‘error‘=> ‘请修改 AllowPrefix 配置项,指定允许上传的路径前缀‘);
        }

        $ShortBucketName = substr($this->config[‘Bucket‘],0, strripos($this->config[‘Bucket‘], ‘-‘));
        $AppId = substr(
上一篇:微信开放平台获取授权公众号的流程


下一篇:C/C++ -- Gui编程 -- Qt库的使用 -- 构造函数中添加组件