阿里雲 oss 視訊上傳 sts+前端js分片上傳
第一步 執行下面藍色程式碼的兩個類 獲取 AccessKeySecretAccessKeyIdSecurityToken 這3個引數(sts)返回的結果下面紅色的部分
{ "RequestId": "0548D3A8-CE25-454A-AD99-02B758CF992D", "AssumedRoleUser": { "AssumedRoleId": "325499844018321549:test", "Arn": "acs:ram::1609196445907631:role/aliyunosstokengeneratorrole/test" }, "Credentials": { "AccessKeySecret": "6jLdHbeUiiLk29eonTwLLiKEgJu8Wpbq26m58vYrHoPe", "AccessKeyId": "STS.NK84yMKu6WW7va1WyMcvfJxCZ", "Expiration": "2018-10-17T03:17:31Z", "SecurityToken": "CAIS/gF1q6Ft5B2yfSjIr4iNf8P5pqoX4JXcdEeAs3kYb/lKpb3ouDz2IHpJeHhhCewatv0/n2pR6/oTlq1vRoRZHe8qmCPwqsY5yxioRqacke7XhOV2pf/IMGyXDAGBr622Su7lTdTbV+6wYlTf7EFayqf7cjPQND7Mc+f+6/hdY88QQxOzYBdfGd5SPXECksIBMmbLPvvfWXyDwEioVRQw61Mt1z8jtPXnnZPHsyCz1gOqlrUnwK3qOYWhYsVWO5Nybsy4xuQedNCainMMukkaqPsu1fwfo26a4oCHcFBV4gSbNe3P6cFoLwJ/aaU8FrRNsP/mj/p8t/wUCkxrQI/IVxqAAbEkcJnat7qTMuyWDAtaSbzSC/yhh40LNE0ddVomBe464G2+92WZtPsSBNT33tNlHItBa9FV6wudlwwDYcmD3b4V3Le9GVDsIQSBor3mpI5R+Rw4BKxZqkM9PacLpC5IuYJtai6vdVdcDaWcyyl6lCxqKnMHPrh1RJqemA+Is9FQ" } }
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/10/7 * Time: 17:43 */ class sysshop_sts_util{ CONST bucket = 'beh'; CONST endpoint = 'oss-cn-beijing.aliyuncs.com'; CONST format = 'json'; CONST version = '2015-04-01'; CONST accesskeyid = 'LTAIZy0T6hrePIVd'; CONST ck = 'CJWJfF9YtmC5tKoKEH6kh5ujMO2LwG'; CONST signaturemethod = 'HMAC-SHA1'; CONST signatureversion = '1.0'; CONST action = 'AssumeRole'; CONST RoleArn = 'acs:ram::1609196445907631:role/aliyunosstokengeneratorrole'; /** * 向oss端post請求 * @param array $data */ public function request_curl(array $data){ $postUrl = 'https://sts.cn-beijing.aliyuncs.com'; $curlPost = $data; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$postUrl); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); $curlCallback = curl_exec($ch); return $curlCallback; curl_close($ch); }
/** * 獲得簽名信息 * @param $get_key * @param $get_key_value * @return string */ public function getsignature($get_key,$get_key_value) { sort($get_key); $StringToSign = 'POST&'.urlencode('/').'&'; $q_str = ''; foreach($get_key as $kval){ $q_str .= urlencode($kval).'='.urlencode($get_key_value[$kval]).'&'; } $q_str = substr($q_str,0,-1); $StringToSign .= urlencode($q_str); return $StringToSign; }
/** * 獲取引數key值 * @return array */ public function getkey() { $get_key = array( 'Format', 'Version', 'AccessKeyId', 'RoleArn', 'RoleSessionName', 'SignatureMethod', 'Timestamp', 'SignatureNonce', 'SignatureVersion', 'Action' ); return $get_key; }
/** * 獲取引數陣列 * @param $RoleSessionName * @return array */ public function getkeyvalue($RoleSessionName) { $h_8_time = time()-8*60*60; $get_key_value = array( 'Format' => self::format, 'RoleArn'=>self::RoleArn, 'RoleSessionName'=>$RoleSessionName, 'Action' => self::action, 'Version' => self::version, 'SignatureMethod' => self::signaturemethod, 'SignatureNonce' => time(), 'SignatureVersion' => self::signatureversion, 'AccessKeyId' =>self::accesskeyid, 'Timestamp' => date('Y-m-d',$h_8_time).'T'.date('H:i:s',$h_8_time).'Z' ); return $get_key_value; } }
/** * Created by PhpStorm. * User: Administrator * Date: 2018/10/7 * Time: 13:12 */ class sysshop_sts_getToken{ CONST bucket = 'beh'; CONST endpoint = 'oss-cn-beijing.aliyuncs.com'; CONST format = 'json'; CONST version = '2015-04-01'; CONST accesskeyid = 'LTAIZy0T6hrePIVd'; CONST ck = 'CJWJfF9YtmC5tKoKEH6kh5ujMO2LwG'; CONST signaturemethod = 'HMAC-SHA1'; CONST signatureversion = '1.0'; CONST action = 'AssumeRole'; CONST RoleArn = 'acs:ram::1609196445907631:role/aliyunosstokengeneratorrole'; private $format; private $version; private $accesskeyid; private $signature; private $signaturemethod; private $signatureversion; private $signaturenonce; private $timestamp; private $action; private $RoleArn; private $RoleSessionName; public function getformat() { return $this->format; } public function getversion() { return $this->version; } public function getaccesskeyid() { return $this->accesskeyid; } public function getsignature() { return $this->signature; } public function getsignaturemethod(){ return $this->signaturemethod; } public function getsignatureversion(){ return $this->signatureversion; } public function getsignaturenonce(){ return $this->signaturenonce; } public function gettimestamp(){ return $this->timestamp; } public function getaction(){ return $this->action; }
/** * @return string */ public function getRoleArn() { return $this->RoleArn; }
/** * @return string */ public function getRoleSessionName() { return $this->RoleSessionName; }
public function index($sessionname) { $sysshop_sts_util = new sysshop_sts_util(); $this->RoleSessionName = $sessionname; $h_8_time = time()-8*60*60; $get_key = $sysshop_sts_util->getkey(); $get_key_value = $sysshop_sts_util->getkeyvalue($this->RoleSessionName); $StringToSign = $sysshop_sts_util->getsignature($get_key,$get_key_value); $this->format = self::format; $this->version = self::version; $this->accesskeyid = self::accesskeyid; $ck = self::ck; $this->signature = base64_encode(hash_hmac("sha1",$StringToSign,$ck.'&',true)); $this->signaturemethod = self::signaturemethod; $this->signatureversion = self::signatureversion; $this->signaturenonce = time(); $this->timestamp = date('Y-m-d',$h_8_time).'T'.date('H:i:s',$h_8_time).'Z'; $this->action = self::action; $this->RoleArn = self::RoleArn; return $sysshop_sts_util->request_curl($this->formatpostdata());
}
/** * 格式化引數 * @return mixed */ public function formatpostdata(){ $data['Format'] = $this->getformat(); $data['Version'] = $this->getversion(); $data['AccessKeyId'] = $this->getaccesskeyid(); $data['Signature'] = $this->getsignature(); $data['SignatureMethod'] = $this->getsignaturemethod(); $data['SignatureVersion'] = $this->getsignatureversion(); $data['SignatureNonce'] = $this->getsignaturenonce(); $data['Timestamp'] = $this->gettimestamp(); $data['Action'] = $this->getaction(); $data['RoleArn'] = $this->getRoleArn(); $data['RoleSessionName'] = $this->getRoleSessionName(); return $data; } } $sysshop_sts_getToken = new sysshop_sts_getToken(); $sessionname = 'test'; $callback = $sysshop_sts_getToken->index($sessionname); print_r($callback);
第二步 前端通過js獲取上面的返回的3個引數實現分片上傳
<html> <head> <script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script> </head> <body> <input type="file" id="file" /> <script type="text/javascript"> document.getElementById('file').addEventListener('change', function (e) { var file = e.target.files[0]; var storeAs = 'upload-file'; console.log(file.name + ' => ' + storeAs); OSS.urllib.request("./upload.php", {method: 'GET'}, function (err, response) { if (err) { return alert(err); } try { result = JSON.parse(response); alert(result.Credentials.AccessKeySecret); } catch (e) { return alert('parse sts response info error: ' + e.message); } var bucket = 'beh';
var callback={ "callbackUrl":"www.58chengcheng.com/test.php", "callbackBody":"mobile=${x:mobile}&type=${x:type}" } //定義callbackbody中需要替換的變數 var callbackvar ={ "x:mobile":"13999999999", "x:type":"1" } //64位編碼 var parses = function(data){ var base = new Base64(); var dataBase64 = base.encode(JSON.stringify(data)) console.log(dataBase64) return dataBase64; } var client = new OSS.Wrapper({ accessKeyId: result.Credentials.AccessKeyId, accessKeySecret: result.Credentials.AccessKeySecret, stsToken: result.Credentials.SecurityToken, endpoint: 'oss-cn-beijing.aliyuncs.com', bucket: 'beh' }); client.multipartUpload(storeAs, file, { //headers 頭引數新增 //x-oss-callback 定義的callbackurl+callbackbody Base64編碼後的值 //x-oss-callback-var 自定義引數值替換callbackbody 變數 headers: { 'x-oss-callback':parses(callback), 'x-oss-callback-var': parses(callbackvar) } }).then(function (res) { console.log(res) }).catch(function (err) { console.log(err); }); }); });
function Base64() {
// private property _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// public method for encoding this.encode = function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = _utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); } return output; }
// public method for decoding this.decode = function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = _keyStr.indexOf(input.charAt(i++)); enc2 = _keyStr.indexOf(input.charAt(i++)); enc3 = _keyStr.indexOf(input.charAt(i++)); enc4 = _keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = _utf8_decode(output); return output; }
// private method for UTF-8 encoding _utf8_encode = function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); }
} return utftext; }
// private method for UTF-8 decoding _utf8_decode = function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } } </script> </body> </html>