阿里雲oss視訊上傳 sts + 前端js分片上傳
阿新 • • 發佈:2018-12-15
getToken.php檔案 <?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/10/7 * Time: 13:12 */ class sysshop_sts_getToken{ 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) { $this->RoleSessionName = $sessionname; $h_8_time = time()-8*60*60; $get_key = kernel::single('sysshop_sts_util')->getkey(); $get_key_value = kernel::single('sysshop_sts_util')->getkeyvalue($this->RoleSessionName); $StringToSign = kernel::single("sysshop_sts_util")->getsignature($get_key,$get_key_value); $this->format = config::get('sts.format'); $this->version = config::get('sts.version'); $this->accesskeyid = config::get('sts.accesskeyid'); $ck = config::get('sts.ck'); $this->signature = base64_encode(hash_hmac("sha1",$StringToSign,$ck.'&',true)); $this->signaturemethod = config::get('sts.signaturemethod'); $this->signatureversion = config::get('sts.signatureversion'); $this->signaturenonce = time(); $this->timestamp = date('Y-m-d',$h_8_time).'T'.date('H:i:s',$h_8_time).'Z'; $this->action = config::get('sts.action'); $this->RoleArn = config::get('sts.RoleArn'); return kernel::single('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; } }
util.php
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/10/7 * Time: 17:43 */ class sysshop_sts_util{ /** * 向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' => config::get('sts.format'), 'RoleArn'=>config::get('sts.RoleArn'), 'RoleSessionName'=>$RoleSessionName, 'Action' => config::get('sts.action'), 'Version' => config::get('sts.version'), 'SignatureMethod' => config::get('sts.signaturemethod'), 'SignatureNonce' => time(), 'SignatureVersion' => config::get('sts.signatureversion'), 'AccessKeyId' =>config::get('sts.accesskeyid'), 'Timestamp' => date('Y-m-d',$h_8_time).'T'.date('H:i:s',$h_8_time).'Z' ); return $get_key_value; } }
stsToken.php
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/10/8 * Time: 10:47 */ class sysshop_api_stsToken{ private $sessionname; private $returndata; public $apiDescription = "獲取ststoken介面"; public function getParams() { $return['params'] = [ 'username' => ['type'=>'string','valid'=>'', 'default'=>'', 'example'=>'', 'description'=>'使用者名稱','default'=>'','example'=>''], ]; return $return; } public function index($params){ $this->sessionname = $params['username']; $this->returndata = kernel::single('sysshop_sts_getToken')->index($this->sessionname); return $this->returndata; } }
ossstsRequest.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/10/10
* Time: 15:19
*/
class sysshop_ctl_ossstsRequest{
/**
* 前端呼叫後端的sts獲取token、accessid、key等值
*/
public function index(){
$ossparam = specialutils::filterInput(input::get());
$ossparam['username'] = 'ffdsf';
try{
$validator = validator::make(
['username'=>$ossparam['username']],
['username'=>'required'],
['username'=>app::get('sysshop')->_('使用者名稱不能為空')]
);
if($validator->fails())
{
$messages = $validator->messages();
throw new LogicException($messages->first());
}
$res = app::get('sysshop')->rpcCall('sts.gettoken',$ossparam);
if($res) {
$res = json_decode($res, 1);
$Credentials = $res['Credentials'];
if ($Credentials) {
$response['bucket'] = config::get('sts.bucket');
$response['endpoint'] = config::get('sts.endpoint');
$response['code'] = '000000';
$response['msg'] = '申請token成功';
$response['Credentials'] = $Credentials;
die(json_encode($response));
} else {
$response['code'] = '000001';
$response['msg'] = '申請token失敗';
die(json_encode($response));
}
}else{
$response['code'] = '000002';
$response['msg'] = '申請token失敗';
die(json_encode($response));
}
}catch(Exception $e){
//待定
// $url = url::action('[email protected]');
// return $this->splash('error',$url, $e->getMessage(),true);
}
}
}
sts.php
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/10/8 * Time: 9:43 */ return array( 'bucket' => '', 'endpoint' => '', 'format' => 'json', 'version' => '', 'accesskeyid' => '', 'ck' => '', 'signaturemethod' => '', 'signatureversion' => '', 'action' => '', 'RoleArn' => '', );
js分片上傳程式碼
<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script> <script> var username = "<{$account.username}>"; var fileDom = document.getElementById('file'); var types = ['rmvb','rm','wmv','avi','3gp','mp4']; var result,file,storeAs = '<{$file.uid}>'; var requestTime = true; var uploadUrl; $('.action-article-save').click(function(){ storeAs = storeAs + '-' + Date.now(); var videoname = $('#videoname').val(); if(!file || !videoname){ return $('#messagebox').message('視訊資訊不完整'); } var callback={ "callbackUrl":"<{$web.url}>/shopadmin?app=sysshop&ctl=ossCallback", "callbackBody":"username=${x:username}&videoname=${x:videoname}&filename=${x:filename}" } //定義callbackbody中需要替換的變數 var callbackvar ={ "x:username": username, "x:videoname": videoname, "x:filename": storeAs } //64位編碼 var parses = function(data){ var base = new Base64(); var dataBase64 = base.encode(JSON.stringify(data)); return dataBase64; } var client = new OSS.Wrapper({ accessKeyId: result.Credentials.AccessKeyId, accessKeySecret: result.Credentials.AccessKeySecret, stsToken: result.Credentials.SecurityToken, endpoint: result.endpoint, bucket: result.bucket }); client.multipartUpload(storeAs, file, { headers: { 'x-oss-callback':parses(callback), 'x-oss-callback-var': parses(callbackvar) } }).then(function (res) { if(res.data.success){ $('#messagebox').message("儲存成功", 'success'); window.location.href = "<{url [email protected]}>"; } }).catch(function (err) { console.log(err); }); }); fileDom.addEventListener('change', function (e) { file = e.target.files[0]; var suffix = file.name.split('.')[1]; if(types.indexOf(suffix.toLowerCase()) <= -1){ return $('#messagebox').message('請上傳正確的視訊檔案'); } $.ajax({ type : "GET", url : "<{$web.url}>/shopadmin?app=sysshop&ctl=ossstsRequest&username="+username, success : function(response) { try{ result = JSON.parse(response); if(window.FileReader) { var reader = new FileReader(); reader.readAsDataURL(file); reader.onload=function(e){ $('.video-box').removeClass('hide'); $('#source').attr('src', this.result); $("#video").load(); } } else { return $('#messagebox').message('原始檔讀取出錯'); } }catch(e){ $('.video-box').hide(); return $('#messagebox').message("上傳失敗"); } } }); }); 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>