oss web直傳

簽名信息javascript

auth.phpphp

<?php
function gmt_iso8601($time) {
    $dtStr = date("c", $time);
    $mydatetime = new DateTime($dtStr);
    $expiration = $mydatetime->format(DateTime::ISO8601);
    $pos = strpos($expiration, '+');
    $expiration = substr($expiration, 0, $pos);
    return $expiration."Z";
}
//阿里雲官方提供的祕鑰
$id= '6MKOqxGiGU4AUk44';
$key= 'ufu7nS8kS59awNihtjSonMETLI0KLy';
$host = 'http://post-test.oss-cn-hangzhou.aliyuncs.com';

$now = time();
$expire = 30; //設置該policy超時時間是10s. 即這個policy過了這個有效時間,將不能訪問
$end = $now + $expire;
$expiration = gmt_iso8601($end);

$dir = 'user-dir/';

//最大文件大小.用戶能夠本身設置
$condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
$conditions[] = $condition;

//表示用戶上傳的數據,必須是以$dir開始, 否則上傳會失敗,這一步不是必須項,只是爲了安全起見,防止用戶經過policy上傳到別人的目錄
$start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
$conditions[] = $start;


$arr = array('expiration'=>$expiration,'conditions'=>$conditions);

$policy = json_encode($arr);
$base64_policy = base64_encode($policy);
$string_to_sign = $base64_policy;
$signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

$response = array();
$response['accessid'] = $id;
$response['host'] = $host;
$response['policy'] = $base64_policy;
$response['signature'] = $signature;
$response['expire'] = $end;
//這個參數是設置用戶上傳指定的前綴
$response['dir'] = $dir;

$response['code']=1;

echo json_encode(['data'=>$response,'status'=>1]);

web端html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>

<div>
    <input type="hidden"  > <img src="" style="width: 200px;height: 100px; display: none">
    <input type="file" name="upfile" accept="image/*" >
</div>


<script type="text/javascript">
    var expire =0;
     sign_obj='';
    var serverUrl='auth.php';
    $(function () {
        $("div").on("change",'input[type="file"]',function(evt){
            $this=$(this);
            var files = evt.target.files;
            var file=files[0];
            if(file.size > 10*1024*1024 ){
                alert('too big');
                return false;
            }
            get_signature();
            if(sign_obj == '') {
                alert(sign_obj);
               alert('簽名error,請重試');
                return false;
            }

            var g_object_name=sign_obj.dir+random_string()+get_suffix(file.name);
            var request = new FormData();
            request.append("OSSAccessKeyId",sign_obj.accessid);//Bucket 擁有者的Access Key Id。
            request.append("policy",sign_obj.policy);//policy規定了請求的表單域的合法性
            request.append("Signature",sign_obj.signature);//根據Access Key Secret和policy計算的簽名信息,OSS驗證該簽名信息從而驗證該Post請求的合法性
            request.append("key",g_object_name);//文件名字,可設置路徑
            request.append("success_action_status",'200');// 讓服務端返回200,否則,默認會返回204
            request.append('x-oss-object-acl', 'public-read');
            request.append('file', file);
            $.ajax({
                url : sign_obj.host,  //上傳阿里地址
                data : request,
                processData: false,//默認true,設置爲 false,不須要進行序列化處理
                cache: false,//設置爲false將不會從瀏覽器緩存中加載請求信息
                async: false,//發送同步請求
                contentType: false,//避免服務器不能正常解析文件---------具體的能夠查下這些參數的含義
                dataType: 'xml',//不涉及跨域  寫json便可
                type : 'post',
                success : function(callbackHost, request) {     //callbackHost:success,request中就是 回調的一些信息,包括狀態碼什麼的
                    var origin=sign_obj.host+'/'+g_object_name;
                    var src=origin;
                    $this.closest('div').find('img').attr('src', src).show();
                    $this.closest('div').find('.imgclose').show();
                },
                error : function(returndata) {
                    console.log("return data:"+returndata);
                    alert('上傳圖片出錯啦,請重試')
                }
            });
        });
    })


    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) {
        var pos = filename.lastIndexOf('.')
        var suffix = ''
        if (pos != -1) {
            suffix = filename.substring(pos)
        }
        return suffix;
    }
    //獲取簽名信息
    function send_request()
    {
        var xmlhttp = null;
        if (window.XMLHttpRequest)
        {
            xmlhttp=new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (xmlhttp!=null)
        {
            xmlhttp.open( "GET", serverUrl, false );
            xmlhttp.send( null );
            return xmlhttp.responseText
        }
        else
        {
            alert("Your browser does not support XMLHTTP.");
        }
    }

    function get_signature()
    {
        //能夠判斷當前expire是否超過了當前時間,若是超過了當前時間,就從新取一下.3s 作爲緩衝
        now = timestamp = Date.parse(new Date()) / 1000;
        if (expire < now + 3)
        {
            var body = send_request();
            var obj =JSON.parse(body);
            if(obj.status ==1  && obj.data.code == 1){
                sign_obj= obj.data;
                expire= parseInt(sign_obj['expire']);
                return true;
            }

            return true;
        }
        return false;
    };


</script>

</body>
</html>
相關文章
相關標籤/搜索