阿里云OSS前端直传(STS临时授权访问)

后端sts支持使用的是php语言,这种方法算是比较安全(个人认为最安全的是前端先上传到后端服务器,再由服务器上传至阿里云OSS,不过这样比较费带宽费时间;或者使用服务端签名直传并设置上传回调)。项目完整源码在文章末尾附有下载地址。

官方说明文档地址:https://help.aliyun.com/document_detail/100624.html?spm=5176.13910061.sslink.10.c9f92bd9AcqfE5

文件夹及文件分布情况:

uoload.js 注意host的值必须与config.json里面的配置保持一致

accessid= '';//值从sts服务器获取即可
accesskey= '';
//host = 'http://post-test.oss-cn-hangzhou.aliyuncs.com';
host='http://public-files.oss-cn-beijing.aliyuncs.com';// 必须与sts 服务器的配置信息一致
//id与key 直接暴露,不建议使用 
token = '';
expire = 0
g_dirname = ''
g_object_name = ''
g_object_name_type = ''
//now = timestamp = Date.parse(new Date()) / 1000; 
var policyText = {
    "expiration": "1990-01-01T12:00:00.000Z", //设置该Policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了--->后期以sts返回的为准
    "conditions": [
    ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
    ]
};

var policyBase64 ='';// Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes ='';// Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
var signature = '';//Crypto.util.bytesToBase64(bytes);


function send_request()//获取id 签名等信息 
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        // serverUrl是 用户获取 '签名和Policy' 等信息的应用服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
        // serverUrl = 'http://88.88.88.88:8888/aliyun-oss-appserver-php/php/get.php'
        //serverUrl = './php/get.php'
        serverUrl = '../sts-server/sts.php'
		
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
};
//get_signature()
function get_signature()
{
    // 可以判断当前expire是否超过了当前时间, 如果超过了当前时间, 就重新取一下,3s 作为缓冲。
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
    	expire=now+60*10;//10分钟有效期,实际以服务器返回的Expiration有效期为准
        body = send_request()
        var obj = eval ("(" + body + ")");
       // host = obj['host']
        //policyBase64 = obj['policy']
        accessid = obj['AccessKeyId']
        //alert(accessid);
        accesskey = obj['AccessKeySecret']
        token = obj['SecurityToken']
      //  signature = obj['signature']
      //  expire = parseInt(obj['Expiration']) ////需要进行转换 "Expiration":"2019-11-03T04:13:14Z"
       // callbackbody = obj['callback'] 
       // key = obj['dir']
       
       policyText["expiration"]=obj['Expiration']
       policyBase64 = Base64.encode(JSON.stringify(policyText))
       message = policyBase64
       bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) 
       signature = Crypto.util.bytesToBase64(bytes);
       /* newwwwwwwwwwwwww
       var policyText = {
    "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了
    "conditions": [
    ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
    ]
};
var policyBase64 = Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
var signature = Crypto.util.bytesToBase64(bytes);
       */
        return true;
    }
    return false;
};

function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ )
    {
        if(tt[i].checked)
        {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}

function get_dirname()
{
    dir = document.getElementById("dirname").value;
    if (dir != '' && dir.indexOf('/') != dir.length - 1)
    {
        dir = dir + '/'
    }
    //alert(dir)
    g_dirname = dir
}

function random_string(len) {
  len = len || 32;
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
  var maxPos = chars.length;
  var pwd = '';
  for (i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name')
    {
        suffix = get_suffix(filename)
        g_object_name = g_dirname + random_string(10) + suffix
    }
    return ''
}

function get_uploaded_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if(g_object_name_type == 'random_name')
    {
        return g_object_name
    }
}

function set_upload_param(up, filename, ret)
{   
     if (ret == false)
    {
        ret = get_signature()
    }///newwwwwwwwwwwwww   
    g_object_name = g_dirname;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'x-oss-security-token':token,
        'success_action_status' : '200', //让服务端返回200,不然,默认会返回204
        'signature': signature,
    };
    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });
    up.start();
}
var uploader = new plupload.Uploader({
	runtimes : 'html5,flash,silverlight,html4',
	browse_button : 'selectfiles', 
    //multi_selection: false,
	container: document.getElementById('container'),
	flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
	silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',
	init: {
		PostInit: function() {
			document.getElementById('ossfile').innerHTML = '';
			document.getElementById('postfiles').onclick = function() {
            set_upload_param(uploader, '', false);
            return false;
			};
		},
		FilesAdded: function(up, files) {
			plupload.each(files, function(file) {				document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
				+'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
				+'</div>';
			});
		},
		BeforeUpload: function(up, file) {
            check_object_radio();
            get_dirname();
            set_upload_param(up, file.name, true);
        },
		UploadProgress: function(up, file) {
			var d = document.getElementById(file.id);
			d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            var prog = d.getElementsByTagName('div')[0];
			var progBar = prog.getElementsByTagName('div')[0]
			progBar.style.width= 2*file.percent+'px';
			progBar.setAttribute('aria-valuenow', file.percent);
		},
		FileUploaded: function(up, file, info) {
            if (info.status == 200)
            {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'upload to oss success, object name:' + get_uploaded_object_name(file.name);
            }
            else
            {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
            } 
		},
		Error: function(up, err) {			document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
		}
	}
});
uploader.init();

config.json

{
"AccessKeyID" : "LTAI4FnFHMcUUtr9P",
"AccessKeySecret" : "MRaya4xBsQaYA9bwknlE8D1",
"RoleArn" : "acs:ram::1971409755302376:role/aliyunosstokengeneratorrole",
"BucketName" : "public-files",
"Endpoint" : "oss-cn-beijing.aliyuncs.com",
"TokenExpireTime" : "900",
"PolicyFile": "policy/bucket_write_policy_full.txt"
}

本sts上传阿里云oss的项目代码已托管码云:https://gitee.com/rorgent/related-to-alibaba-cloud/tree/master/%E9%98%BF%E9%87%8C%E4%BA%91oss%E5%89%8D%E7%AB%AF%E7%9B%B4%E4%BC%A0STS

基于互联网精神,在注明出处的前提下本站文章可自由转载!

本文链接:https://ranjuan.cn/aliyun-oss-sts/

赞赏

微信赞赏支付宝赞赏

发表评论