2020-02-25 17:56:35  5274 0

webuploader+oss+tp5.1文件直传

 标签:   


webuploader代码


<script>
        var uploader = WebUploader.create({
                auto: false,
        // swf文件路径
        swf: '/static/webuploader/0.1.5/Uploader.swf',

        // 文件接收服务端。
        server: 'http://lampol-3.oss-cn-beijing.aliyuncs.com',

        // 内部根据当前运行是创建,可能是input元素,也可能是flash.
        pick: '#picker',
        // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
        resize: false
        });

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

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


        uploader.on('uploadBeforeSend',function(obj,data,header){


                file_name = get_file_name(data.name)


                $.ajaxSettings.async = false;
                $.get('/getSign',function(info,staus){
                        info= JSON.parse(info);
                        data = $.extend(data , {
                                'key':info.dir+file_name,
                                'policy':info.policy,
                                'OSSAccessKeyId':info.accessid,
                                'success_action_status':'200',
                                'callback':info.callback,
                                'signature':info.signature
                        });

                });

        });

        $("#ctlBtn").on("click",function (obj) {
          uploader.upload();
    })

        uploader.on( 'uploadProgress', function( file, percentage ) {
                obj = $('#progress');
                if(JSON.stringify(obj) == '{}'){
                        $('#uploader').append('<progress id="progress" value=0  max="1" ></progress>');
                }else{
                        obj.attr({value:percentage});
                }
        });
        uploader.on( 'uploadSuccess', function( file,msg ) {
                console.log(msg)
        });


</script>


php签名


public function getSign(){
                $id= config('oss.AccessKeyID');          // 请填写您的AccessKeyId。
        $key= config('oss.AccessKeySecret');     // 请填写您的AccessKeySecret。
            $host = config('oss.Bucket').'.'.config('oss.Endpoint');  
            $callbackUrl = config('oss.Callback');
            $dir = config('oss.Dir');          // 用户上传文件时指定的前缀。

            $callback_param = array('callbackUrl'=>$callbackUrl, 
                         'callbackBody'=>'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}', 
                         'callbackBodyType'=>"application/x-www-form-urlencoded");
            $callback_string = json_encode($callback_param);

            $base64_callback_body = base64_encode($callback_string);
            $now = time();
            $expire = 30;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间,将不能访问。
            $end = $now + $expire;
            $expiration = $this->gmt_iso8601($end);


            //最大文件大小.用户可以自己设置
            $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['callback'] = $base64_callback_body;
            $response['dir'] = $dir;  // 这个参数是设置用户上传文件时指定的前缀。
            return  json_encode($response);

        }


php回调代码


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


        public function  callback(){
                // 1.获取OSS的签名header和公钥url header
                $authorizationBase64 = "";
                $pubKeyUrlBase64 = "";
                /*
                 * 注意:如果要使用HTTP_AUTHORIZATION头,你需要先在apache或者nginx中设置rewrite,以apache为例,修改
                 * 配置文件/etc/httpd/conf/httpd.conf(以你的apache安装路径为准),在DirectoryIndex index.php这行下面增加以下两行
                    RewriteEngine On
                    RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]
                 * */
                if (isset($_SERVER['HTTP_AUTHORIZATION']))
                {
                    $authorizationBase64 = $_SERVER['HTTP_AUTHORIZATION'];
                }
                if (isset($_SERVER['HTTP_X_OSS_PUB_KEY_URL']))
                {
                    $pubKeyUrlBase64 = $_SERVER['HTTP_X_OSS_PUB_KEY_URL'];
                }

                if ($authorizationBase64 == '' || $pubKeyUrlBase64 == '')
                {
                    header("http/1.1 403 Forbidden");
                    exit();
                }

                // 2.获取OSS的签名
                $authorization = base64_decode($authorizationBase64);

                // 3.获取公钥
                $pubKeyUrl = base64_decode($pubKeyUrlBase64);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $pubKeyUrl);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                $pubKey = curl_exec($ch);
                if ($pubKey == "")
                {
                    //header("http/1.1 403 Forbidden");
                    exit();
                }

                // 4.获取回调body
                $body = file_get_contents('php://input');

                parse_str($body,$body_arr);
                // 5.拼接待签名字符串
                $authStr = '';
                $path = $_SERVER['REQUEST_URI'];
                $pos = strpos($path, '?');
                if ($pos === false)
                {
                    $authStr = urldecode($path)."\n".$body;
                }
                else
                {
                    $authStr = urldecode(substr($path, 0, $pos)).substr($path, $pos, strlen($path) - $pos)."\n".$body;
                }

                // 6.验证签名
                $ok = openssl_verify($authStr, $authorization, $pubKey, OPENSSL_ALGO_MD5);
                if ($ok == 1)
                {
                    header("Content-Type: application/json");
                    $data = array("Status"=>"Ok",'url'=>$body_arr['filename']);
                    return  json_encode($data);
                }
                else
                {
                    //header("http/1.1 403 Forbidden");
                    exit();
                }

        }


oss.php  配置代码


return [
        'AccessKeyID'=>'',
        'AccessKeySecret'=>'',
        'Bucket'=>'',
        'Endpoint'=>'',
        'Dir'=>'image/',
        'Callback'=>''

];


0 条留言此文章没有人评论

给我留言

评论内容