1. 程式人生 > >微信小程序/網站 上傳圖片到騰訊雲COS

微信小程序/網站 上傳圖片到騰訊雲COS

arr n) ram index.php 函數返回 tps etag 循環 5.0

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:[email protected] | 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($this->config[‘Bucket‘], 1 + strripos($this->config[‘Bucket‘], ‘-‘));
        $policy = array(
            ‘version‘=> ‘2.0‘,
            ‘statement‘=> array(
                array(
                    ‘action‘=> array(
                        // 簡單文件操作
                        ‘name/cos:PutObject‘,
                        ‘name/cos:PostObject‘,
                        ‘name/cos:AppendObject‘,
                        ‘name/cos:GetObject‘,
                        ‘name/cos:HeadObject‘,
                        ‘name/cos:OptionsObject‘,
                        ‘name/cos:PutObjectCopy‘,
                        ‘name/cos:PostObjectRestore‘,
                        // 分片上傳操作
                        ‘name/cos:InitiateMultipartUpload‘,
                        ‘name/cos:ListMultipartUploads‘,
                        ‘name/cos:ListParts‘,
                        ‘name/cos:UploadPart‘,
                        ‘name/cos:CompleteMultipartUpload‘,
                        ‘name/cos:AbortMultipartUpload‘,
                    ),
                    ‘effect‘=> ‘allow‘,
                    ‘principal‘=> array(‘qcs‘=> array(‘*‘)),
                    ‘resource‘=> array(
                        ‘qcs::cos:‘ . $this->config[‘Region‘] . ‘:uid/‘ . $AppId . ‘:prefix//‘ . $AppId . ‘/‘ . $ShortBucketName . ‘/‘,
                        ‘qcs::cos:‘ . $this->config[‘Region‘] . ‘:uid/‘ . $AppId . ‘:prefix//‘ . $AppId . ‘/‘ . $ShortBucketName . ‘/‘ . $this->config[‘AllowPrefix‘]
                    )
                )
            )
        );

        $policyStr = str_replace(‘\\/‘, ‘/‘, json_encode($policy));
        $Action = ‘GetFederationToken‘;
        $Nonce = rand(10000, 20000);
        $Timestamp = time() - 1;
        $Method = ‘GET‘;

        $params = array(
            ‘Action‘=> $Action,
            ‘Nonce‘=> $Nonce,
            ‘Region‘=> ‘‘,
            ‘SecretId‘=> $this->config[‘SecretId‘],
            ‘Timestamp‘=> $Timestamp,
            ‘durationSeconds‘=> 7200,
            ‘name‘=> ‘‘,
            ‘policy‘=> $policyStr
        );
        $params[‘Signature‘] = urlencode($this->getSignature($params, $this->config[‘SecretKey‘], $Method));

        $url = $this->config[‘Url‘] . ‘?‘ . $this->json2str($params, 1);
        $ch = curl_init($url);
        $this->config[‘Proxy‘] && curl_setopt($ch, CURLOPT_PROXY, $this->config[‘Proxy‘]);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        if(curl_errno($ch)) $result = curl_error($ch);
        curl_close($ch);

        $result = json_decode($result, 1);
        $_SESSION[‘tempKeysCache‘] = $result[‘data‘];
        $_SESSION[‘tempKeysCache‘][‘policyStr‘] = $policyStr;

        return $result[‘data‘];
    }

    // 計算 COS API 請求用的簽名
    public function getAuthorization($keys, $method, $pathname)
    {

        // 獲取個人 API 密鑰 https://console.qcloud.com/capi
        $SecretId = $keys[‘credentials‘][‘tmpSecretId‘];
        $SecretKey = $keys[‘credentials‘][‘tmpSecretKey‘];

        // 整理參數
        $query = array();
        $headers = array();
        $method = strtolower($method ? $method : ‘get‘);
        $pathname = $pathname ? $pathname : ‘/‘;
        substr($pathname, 0, 1) != ‘/‘ && ($pathname = ‘/‘ . $pathname);

        // 工具方法
        function getObjectKeys($obj)
        {
            $list = array_keys($obj);
            sort($list);
            return $list;
        }

        function obj2str($obj)
        {
            $list = array();
            $keyList = getObjectKeys($obj);
            $len = count($keyList);
            for ($i = 0; $i < $len; $i++) {
                $key = $keyList[$i];
                $val = $obj[$key] ? $obj[$key] : ‘‘;
                $key = strtolower($key);
                $list[] = rawurlencode($key) . ‘=‘ . rawurlencode($val);
            }
            return implode(‘&‘, $list);
        }

        // 簽名有效起止時間
        $now = time() - 1;
        $expired = $now + 3600; // 簽名過期時刻,600 秒後

        // 要用到的 Authorization 參數列表
        $qSignAlgorithm = ‘sha1‘;
        $qAk = $SecretId;
        $qSignTime = $now . ‘;‘ . $expired;
        $qKeyTime = $now . ‘;‘ . $expired;
        $qHeaderList = strtolower(implode(‘;‘, getObjectKeys($headers)));
        $qUrlParamList = strtolower(implode(‘;‘, getObjectKeys($query)));


        // 簽名算法說明文檔:https://www.qcloud.com/document/product/436/7778
        // 步驟一:計算 SignKey
        $signKey = hash_hmac("sha1", $qKeyTime, $SecretKey);

        // 步驟二:構成 FormatString
        $formatString = implode("\n", array(strtolower($method), $pathname, obj2str($query), obj2str($headers), ‘‘));

        // 自定義頭部(暫時關閉)
        // header(‘x-test-method‘, $method);
        // header(‘x-test-pathname‘, $pathname);

        // 步驟三:計算 StringToSign
        $stringToSign = implode("\n", array(‘sha1‘, $qSignTime, sha1($formatString), ‘‘));

        // 步驟四:計算 Signature
        $qSignature = hash_hmac(‘sha1‘, $stringToSign, $signKey);

        // 步驟五:構造 Authorization
        $authorization = implode(‘&‘, array(
            ‘q-sign-algorithm=‘ . $qSignAlgorithm,
            ‘q-ak=‘ . $qAk,
            ‘q-sign-time=‘ . $qSignTime,
            ‘q-key-time=‘ . $qKeyTime,
            ‘q-header-list=‘ . $qHeaderList,
            ‘q-url-param-list=‘ . $qUrlParamList,
            ‘q-signature=‘ . $qSignature
        ));

        return $authorization;
    }

 /*********************************************************************************************************************************************/

//     // cos配置參數
//     protected $config = array(
//         ‘Url‘         => ‘https://sts.api.qcloud.com/v2/index.php‘,
//         ‘Domain‘      => ‘sts.api.qcloud.com‘,   
//         ‘Proxy‘       => ‘‘,
//         ‘SecretId‘    => ‘AKIDwqbCewU2ZxABC3QDWp1EWrBLK9nF5dZL‘, // 固定密鑰
//         ‘SecretKey‘   => ‘jHj5GIAvV8eFk3B8tSwKXYO4f0IUcqJu‘,     // 固定密鑰
//         ‘Bucket‘      => ‘xcx-1255484416‘,
//         ‘Region‘      => ‘ap-guangzhou‘,
//         ‘AllowPrefix‘ => ‘*‘, // 這裏改成允許的路徑前綴,這裏可以根據自己網站的用戶登錄態判斷允許上傳的目錄,例子:* 或者 a/* 或者 a.jpg
//     );
//     // $config = array(
//     //     ‘Url‘ => ‘https://sts.api.qcloud.com/v2/index.php‘,
//     //     ‘Domain‘ => ‘sts.api.qcloud.com‘,
//     //     ‘Proxy‘ => ‘‘,
//     //     ‘SecretId‘ => ‘AKIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx‘, // 固定密鑰
//     //     ‘SecretKey‘ => ‘xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx‘, // 固定密鑰
//     //     ‘Bucket‘ => ‘test-1250000000‘,
//     //     ‘Region‘ => ‘ap-guangzhou‘,
//     //     ‘AllowPrefix‘ => ‘_ALLOW_DIR_/*‘, // 必填,這裏改成允許的路徑前綴,這裏可以根據自己網站的用戶登錄態判斷允許上傳的目錄,例子:* 或者 a/* 或者 a.jpg
//     // );
//     // json 轉 query string
//     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);
//     }

//     // 計算臨時密鑰用的簽名
//     function getSignature($opt, $key, $method) 
//     {

//         $formatString = $method . $this->config[‘Domain‘] . ‘/v2/index.php?‘ . self::json2str($opt, 1);
//         $sign = hash_hmac(‘sha1‘, $formatString, $key);
//         $sign = base64_encode(hex2bin($sign));
//         return $sign;
//     }

//     // 獲取臨時密鑰
//     function getTempKeys() 
//     {
//         // 判斷是否修改了 AllowPrefix
//         if ($this->config[‘AllowPrefix‘] === ‘_ALLOW_DIR_/*‘) {
//             return array(‘error‘=> ‘請修改 AllowPrefix 配置項,指定允許上傳的路徑前綴‘);
//         }
// // dump($this->config);
//         $ShortBucketName = substr($this->config[‘Bucket‘],0, strripos($this->config[‘Bucket‘], ‘-‘));
//         $AppId = substr($this->config[‘Bucket‘], 1 + strripos($this->config[‘Bucket‘], ‘-‘));
//         $policy = array(
//             ‘version‘=> ‘2.0‘,
//             ‘statement‘=> array(
//                 array(
//                     ‘action‘=> array(
//                         // // 這裏可以從臨時密鑰的權限上控制前端允許的操作
//                           ‘name/cos:*‘, // 這樣寫可以包含下面所有權限
//                         // // 列出所有允許的操作
//                         // // ACL 讀寫
//                         // ‘name/cos:GetBucketACL‘,
//                         // ‘name/cos:PutBucketACL‘,
//                         // ‘name/cos:GetObjectACL‘,
// // ‘name/cos:PutObjectACL‘, // // // 簡單 Bucket 操作 // // ‘name/cos:PutBucket‘, // // ‘name/cos:HeadBucket‘, // // ‘name/cos:GetBucket‘, // // ‘name/cos:DeleteBucket‘, // // ‘name/cos:GetBucketLocation‘,
// // // Versioning // // ‘name/cos:PutBucketVersioning‘, // // ‘name/cos:GetBucketVersioning‘, // // // CORS // // ‘name/cos:PutBucketCORS‘, // // ‘name/cos:GetBucketCORS‘, // // ‘name/cos:DeleteBucketCORS‘, // // // Lifecycle // // ‘name/cos:PutBucketLifecycle‘, // // ‘name/cos:GetBucketLifecycle‘, // // ‘name/cos:DeleteBucketLifecycle‘, // // // Replication // // ‘name/cos:PutBucketReplication‘, // // ‘name/cos:GetBucketReplication‘, // // ‘name/cos:DeleteBucketReplication‘, // // // 刪除文件 // // ‘name/cos:DeleteMultipleObject‘, // // ‘name/cos:DeleteObject‘, // // 簡單文件操作 // ‘name/cos:PutObject‘, // ‘name/cos:PostObject‘, // ‘name/cos:AppendObject‘, // ‘name/cos:GetObject‘, // ‘name/cos:HeadObject‘, // ‘name/cos:OptionsObject‘, // ‘name/cos:PutObjectCopy‘, // ‘name/cos:PostObjectRestore‘, // // 分片上傳操作 // ‘name/cos:InitiateMultipartUpload‘, // ‘name/cos:ListMultipartUploads‘, // ‘name/cos:ListParts‘, // ‘name/cos:UploadPart‘, // ‘name/cos:CompleteMultipartUpload‘, // ‘name/cos:AbortMultipartUpload‘, // ), // ‘effect‘=> ‘allow‘, // ‘principal‘=> array(‘qcs‘=> array(‘*‘)), // ‘resource‘=> array( // ‘qcs::cos:‘ . $this->config[‘Region‘] . ‘:uid/‘ . $AppId . ‘:prefix//‘ . $AppId . ‘/‘ . $ShortBucketName . ‘/‘, // ‘qcs::cos:‘ . $this->config[‘Region‘] . ‘:uid/‘ . $AppId . ‘:prefix//‘ . $AppId . ‘/‘ . $ShortBucketName . ‘/‘ . $this->config[‘AllowPrefix‘] // ) // ) // ) // ); // $policyStr = str_replace(‘\\/‘, ‘/‘, json_encode($policy)); // $Action = ‘GetFederationToken‘; // $Nonce = rand(10000, 20000); // $Timestamp = time() - 1; // $Method = ‘GET‘; // $params = array( // ‘Action‘=> $Action, // ‘Nonce‘=> $Nonce, // ‘Region‘=> ‘‘, // ‘SecretId‘=> $this->config[‘SecretId‘], // ‘Timestamp‘=> $Timestamp, // ‘durationSeconds‘=> 7200, // ‘name‘=> ‘‘, // ‘policy‘=> $policyStr // ); // $params[‘Signature‘] = urlencode(self::getSignature($params, $this->config[‘SecretKey‘], $Method)); // $url = $this->config[‘Url‘] . ‘?‘ . self::json2str($params, 1); // $ch = curl_init($url); // $this->config[‘Proxy‘] && curl_setopt($ch, CURLOPT_PROXY, $this->config[‘Proxy‘]); // curl_setopt($ch, CURLOPT_HEADER, 0); // curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0); // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // $result = curl_exec($ch); // if(curl_errno($ch)) $result = curl_error($ch); // curl_close($ch); // $result = json_decode($result, 1); // return $result[‘data‘]; // } // public function getCosAuth() // { // // 獲取臨時密鑰,計算簽名 // $tempKeys = self::getTempKeys(); // // 返回數據給前端 // header(‘Content-Type: application/json‘); // header(‘Allow-Control-Allow-Origin: *‘); // 這裏修改允許跨域訪問的網站 // header(‘Allow-Control-Allow-Headers: origin,accept,content-type‘); // echo json_encode($tempKeys); // } }

二、javascript上傳圖片部分

首先去騰旭雲下載cos-js-sdk-v5.min.js並引入頁面,這裏只展示實現部分

// 圖片上傳監聽事件
function uploadConver(_this,event) {

	for(var i = 0;i<event.target.files.length;i++) {
        var files = event.target.files[i];

        if (!files) {
			tipPopup(‘未選擇上傳文件‘,1100,4);
			return;
		}

		files && uploadFile(files, function (err, data) {

			if(data) {
				$("#preImg").html("").append(‘<img src="‘+data.url+‘" width="200px"/>‘);
				//$("#conver").val(data.url);
				console.log(data);
			}else {
				console.log(err);
			}

			//console.log(err || data);
			//document.getElementById(‘msg‘).innerText = err ? err : (‘上傳成功,ETag=‘ + data.ETag);
		});
        //uploadFileToOss(file);
        //console.log(file);
    }
}

// 異步請求上傳簽名
var getAuthorization = function (options, callback) {
        
     var xhr = new XMLHttpRequest();
     xhr.open(‘GET‘, url, true);
     xhr.onload = function (e) {
         var AuthData;
         try {
             AuthData = JSON.parse(xhr.responseText)
         } catch (e) {}
         if (AuthData && AuthData.Authorization) {
             callback(null, {
                 Authorization: AuthData.Authorization,
                 XCosSecurityToken: AuthData.XCosSecurityToken,
             });
            
         } else {
         	// alert(123);
             console.error(AuthData);
             callback(‘獲取簽名出錯‘);
         }
     };
     xhr.onerror = function (e) {
         callback(‘獲取簽名出錯‘);
     };
     xhr.send();
};

// 上傳文件(真正上傳到COS)
var uploadFile = function (file, callback) {

	if(file.size>1024*1024*2) {		// 限制圖片大小2M
		layer.open({content: ‘上傳的圖片不能超過 2MB‘,skin: ‘msg‘,time: 3 });
		//tipPopup("上傳的圖片不能超過 2MB",1100,3);
		return;
	}

	if(file.type != ‘image/jpeg‘ && file.type != ‘image/png‘ && file.type != ‘image/gif‘) {		// 限制圖片格式
		layer.open({content: ‘上傳圖片的格式不正確‘,skin: ‘msg‘,time: 3 });
		//tipPopup("上傳圖片的格式不正確",1100,3);
		return;
	}

	// 檢測文件名不能含有中文漢字
	if(escape(file.name).indexOf(‘%u‘) != -1) {
		layer.open({content: ‘上傳的文件名有中文,請重新上傳‘,skin: ‘msg‘,time: 3 });
		return;
	}

	var dirBase = ‘temp2018/‘;
	var myDate = new Date();
	var reg = new RegExp( ‘/‘ , "g" );

	// var specilReg = /[@#\$\!()%-~+\^&\s*]+/g;;	// 過濾文件名的特殊字符
	// var fileName = file.name.replace(specilReg,‘‘);
	var files = (myDate.toLocaleDateString()).replace(reg,"")+‘/‘+myDate.getTime()+‘_‘+parseInt(Math.random()*100000)+‘_‘+file.name;
    var Key = dirBase+ files; // 這裏指定上傳目錄和文件名
    
    // 執行獲取簽名函數,拿到簽名通過回調上傳
    getAuthorization({Method: ‘POST‘, Key: Key}, function (err, info) {
    	
        var fd = new FormData();
        fd.append(‘key‘, Key);
        fd.append(‘Signature‘, info.Authorization);
        fd.append(‘Content-Type‘, ‘‘);
        info.XCosSecurityToken && fd.append(‘x-cos-security-token‘, info.XCosSecurityToken);
        fd.append(‘file‘, file);
        var url = prefix;
        var xhr = new XMLHttpRequest();
        xhr.open(‘POST‘, url, true);
        xhr.onload = function () {
            if (Math.floor(xhr.status / 100) === 2) {
                var ETag = xhr.getResponseHeader(‘etag‘);
                callback(null, {url: url+Key, ETag: ETag});
            }else {
                callback(‘文件 ‘ + Key + ‘ 上傳失敗,狀態碼:‘ + xhr.status);
            }
        };
        xhr.onerror = function () {
            callback(‘文件 ‘ + Key + ‘ 上傳失敗,請檢查是否沒配置 CORS 跨域規則‘);
        };
        $("#preImg").html("").append(‘<span style="color:red">上傳中……</span>‘);
        xhr.send(fd);

    });
};

----------------------------------------------------------------------------------------------------------

三、微信小程序上傳方式

這裏小程序就演示直接自己生成簽名,然後通過cos的SDK提供的函數上傳。

1.config.js 單獨配置

var config = {
   Bucket: ‘busin-1256537792‘,//存儲桶
    Region: ‘ap-guangzhou‘,//地域
    SecretId: ‘AKIDTtR************XiiW8nLLlp39yl4LW‘, 
    SecretKey: ‘hslO1YxFNJ5lGh0yR7c4Qemi8VhPRhmf‘, //replace with yours
}

module.exports = config

2.實現上傳功能

/*
*author: fuchao
*date: 2018-04-27
*desc: 小程序本地簽名上傳圖片到騰訊雲cos
*個人公眾號: ZEROFC_DEV
**/

// 同樣需要先引入COS的SDK,和配置文件
var COS = require(‘../../lib/cos-wx-sdk-v5‘);
var config = require(‘./config‘);

// 實例COS
var cos = new COS({
    getAuthorization: function (params, callback) {	//獲取簽名
        var authorization = COS.getAuthorization({
            SecretId: config.SecretId,
            SecretKey: config.SecretKey,
            Method: params.Method,
            Key: params.Key
        });
        callback(authorization);
    }
});

Page({
  data: {
    list: [],
  },
  simpleUpload: function() {
    // 選擇文件
    wx.chooseImage({
      count: 4, // 默認9
      sizeType: [‘original‘, ‘compressed‘], // 可以指定是原圖還是壓縮圖,默認二者都有
      sourceType: [‘album‘, ‘camera‘], // 可以指定來源是相冊還是相機,默認二者都有
      success: function (res) {
        var filePath = res.tempFilePaths[0]
        var Key = filePath.substr(filePath.lastIndexOf(‘/‘) + 1); // 這裏指定上傳的文件名
        var dateObj = new Date();
        var timestamp = dateObj.getTime();
        var nowDate = dateObj.toLocaleDateString();
        var formatDate = nowDate.replace(/\//g,"-");  // 格式斜杠日期
        console.log(formatDate);
        var newKey = formatDate + ‘/‘ + timestamp+Key;   // cos上定義目錄
        var tempObj = {};
        tempObj.imgLocation = ‘https://‘ + config.Bucket + ‘.cos.‘ + config.Region + ‘.myqcloud.com/‘ + newKey; // 返回上傳的絕對URL

        // sdk提供的COS上傳函數,如果想批量上傳,在這裏加FOR循環即可。
        cos.postObject({
          Bucket: config.Bucket,  // 存儲桶
          Region: config.Region,  // 地域
          Key: newKey,
          FilePath: filePath,     // 本地文件臨時地址
          // onProgress: function (info) {   // 上傳時基本信息
          //   console.log(JSON.stringify(info));
          // }
        },requestCallback(null,tempObj));
      }
    })
  },
});

// 上傳圖片回調函數
var requestCallback = function (err, data) {
  console.log(err || data);
  if (err && err.error) {
    wx.showModal({ title: ‘返回錯誤‘, content: ‘請求失敗:‘ + err.error.Message + ‘;狀態碼:‘ + err.statusCode, showCancel: false });
  } else if (err) {
    wx.showModal({ title: ‘請求出錯‘, content: ‘請求出錯:‘ + err + ‘;狀態碼:‘ + err.statusCode, showCancel: false });
  } else {
    console.log(data);
    wx.showToast({ title: ‘請求成功‘, icon: ‘success‘, duration: 3000 });
  }
};


個人避坑解決方案

原因:開始上傳圖片到cos的項目我是用TP3.2做的,但是上傳到linux且高版本的php服務器上,發現我那個生成簽名的php竟然報500錯誤,而我本地是windows且php版本低於5.5一切都很正常。至於是什麽原因,我也沒時間去解決,只能把生成簽名的php文件改成tp5.0的放在另一個項目中,而我就以跨域的方式去請求簽名。

1.php文件修改

// 增加跨域響應頭
header(‘Content-Type: application/json‘);
header(‘Allow-Control-Allow-Origin: *‘);       // 這裏修改允許跨域訪問的網站
header(‘Allow-Control-Allow-Headers: origin,accept,content-type‘);

// 增加前端jsonp參數
$callback = input(‘callback‘) ? input(‘callback‘) : ‘‘;

// 以回調函數返回簽名到前端
echo $callback . ‘(‘ . json_encode($data) . ‘)‘;

2.js部分修改(主要改成跨域請求簽名)

// 計算簽名
var getAuthorization = function (options, callback) {
    var baseUrl = $("#cosurl").attr("urls");
    var url = baseUrl;

    $.ajax({    
        url:url,    
        dataType: ‘jsonp‘,  //類型
        jsonp: "callback",  // 參數    後臺接受的是回掉函數名 
        //data:"",  
        type:‘get‘,
        success: function(result) {
            callback(null, {
                Authorization: result.Authorization,    // 跨域拿到簽名
                XCosSecurityToken: result.XCosSecurityToken,
            });

        },  
        error:function(result) {  
            callback(‘獲取簽名出錯‘);
        }
    })
};

個人微信公眾號

技術分享圖片

微信小程序/網站 上傳圖片到騰訊雲COS