1. 程式人生 > >thinkphp OSS伺服器簽名直傳

thinkphp OSS伺服器簽名直傳

<?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";
}

function oss_qianming(){
    $id= 'XXX';
    $key= 'XXX';
    $host = 'http://XXX.oss-cn-beijing.aliyuncs.com';

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

    $dir = 'upload/'. date("Ymd",time()) .'/';

    //最大檔案大小.使用者可以自己設定
    $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);
    //echo json_encode($arr);
    //return;
    $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;
    return $response;
}






    
    //控制器
    public function edit($id)
    {
        $taoxi = $this->taoxi_model->find($id);
        $oss_qianming = oss_qianming();

        return $this->fetch('edit', ['taoxi' => $taoxi, 'oss_qianming' => $oss_qianming]);
    }


?>


<!--
edit.html
-->
<div class="layui-form-item">
    <label class="layui-form-label">套系視訊</label>
    <div class="layui-input-block">
        <input type="text" name="video" value="{$taoxi.video}" class="layui-input">
    </div>
    <div class="layui-input-block">
        <a id="up_video_box_file" href="javascript:void(0);" class='layui-btn'>選擇檔案</a>
        <div id="up_video_box_msg" style="line-height:40px;"></div>
    </div>
</div>


<script>
var policy = '{$oss_qianming.policy}';
var signature = '{$oss_qianming.signature}';
var dir = '{$oss_qianming.dir}';
oss_zhichuan('up_audio_box_file','up_audio_box_msg','audio');


accessid= 'XXX';
host = 'http://XXX.oss-cn-beijing.aliyuncs.com';

/**
 * OSS直傳
 * @param file_btn  上傳按鈕
 * @param msg       上傳檔案資訊
 * @param file_ipt  儲存上傳檔案path的input
 * @return 
 */
function oss_zhichuan(file_btn,msg_div,file_ipt)
{
var uploader = new plupload.Uploader({
    runtimes : 'html5,flash,silverlight,html4',
    browse_button : file_btn, 
    flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
    multi_selection : false,//設定不允許一次上傳多個
    url : host,
    multipart_params: {
        'Filename': '${filename}', 
        'key' : dir+'${filename}',
        'policy': policy,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //讓服務端返回200,不然,預設會返回204
        'signature': signature,
    },
    init: {
        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>';
                document.getElementById(msg_div).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>';

                previewImage(file,function(imgsrc){
                    $('#'+file.id).append('<img src="'+ imgsrc +'" />');
                })

            });


            uploader.start();

        },
        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 || info.status < 200)
            {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上傳成功!';
                
                var name = dir+file.name;
                $("input[name='"+file_ipt+"']").val(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();
}

    //plupload中為我們提供了mOxie物件
    //有關mOxie的介紹和說明請看:https://github.com/moxiecode/moxie/wiki/API
    //如果你不想了解那麼多的話,那就照抄本示例的程式碼來得到預覽的圖片吧
    function previewImage(file,callback){//file為plupload事件監聽函式引數中的file物件,callback為預覽圖片準備完成的回撥函式
        if(!file || !/image\//.test(file.type)) return; //確保檔案是圖片
        if(file.type=='image/gif'){//gif使用FileReader進行預覽,因為mOxie.Image只支援jpg和png
            var fr = new mOxie.FileReader();
            fr.onload = function(){
                callback(fr.result);
                fr.destroy();
                fr = null;
            }
            fr.readAsDataURL(file.getSource());
        }else{
            var preloader = new mOxie.Image();
            preloader.onload = function() {
                preloader.downsize( 300, 300 );//先壓縮一下要預覽的圖片,寬300,高300
                var imgsrc = preloader.type=='image/jpeg' ? preloader.getAsDataURL('image/jpeg',80) : preloader.getAsDataURL(); //得到圖片src,實質為一個base64編碼的資料
                callback && callback(imgsrc); //callback傳入的引數為預覽圖片的url
                preloader.destroy();
                preloader = null;
            };
            preloader.load( file.getSource() );
        }   
    }


</script>