tp5.1 乐视云上传视频文件(https请求http乐视云上传接口)http网址下上传视频(https API接口)

一、sdk_php_v2.0.zip 上传视频

网址:http://www.lecloud.com/zh-cn/help/api.html

tp5.1 乐视云上传视频文件(https请求http乐视云上传接口)

乐视云上传视频接口都是http,以为是没有https接口文档的,

而自己系统域名是https的,

修改自适应

观察:

如果上传成功,会安顺序出现下面三个网址

分析第一个网址

如果虽https中请求时,在第二个网址时候换成upload_https_url这个网址来请求就可以了

修改js

                        if(protocolStr == "http:"){
                           var url = data.data.upload_url;
                        }else if(protocolStr == "https:"){
                            var url = data.data.upload_https_url;
                        }

1、模板html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!--<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">-->
<title>上传视频_乐视云</title>
<link rel="stylesheet" href="__STATIC__/layui/css/layui.css" media="all">
<script src="__STATIC__/layui/layui.js"></script>
<!--乐视云上传 开始-->
    <!--<script type="text/javascript" src="__STATIC__/jquery/1.8.3/jquery.min.js"></script>-->
    <!--<script src="__STATIC__/admin/lecloud/upload_sdk.js" type="text/javascript" charset="utf-8"></script>-->
	<script type="text/javascript" src="__STATIC__/admin/lecloud//jquery.js"></script>
	<script type="text/javascript" src="__STATIC__/admin/lecloud//jquery.form.js"></script>
	<script type="text/javascript" src="__STATIC__/admin/lecloud//formUpload.js"></script>
<!--乐视云上传 结束-->
</head>

<body style="background-color: #FFFFFF;">
<div class="layui-fluid" style="margin-top: 20px;">
	
		<table class="layui-table">
		    <thead>
		    <tr>
		        <th>视频名称</th>
		        <th>上传进度</th>
		        <th>上传速度</th>
		        <th>上传状态</th>
		    </tr>
		    </thead>
		    <tbody>
		    <tr>
		        <td id="videoId"></td>
		        <td id="videoProgress"></td>
		        <td id="videoSpeed"></td>
		        <td id="videoStatus"></td>
		    </tr>
		    </tbody>
		</table>
		<div>
		    <input type="button" class="uploadBtn" id="uploadBtn" value="开始上传" />
		    <input type="button" class="uploadBtn" id='fileSelecter' value="添加视频" />
		</div>

</div>

<script>
//注意:折叠面板 依赖 element 模块,否则无法进行功能性操作
layui.use(['layer','element','jquery'], function(){
     var element = layui.element,
     $ = layui.jquery,
     layer = layui.layer;
     

  
});
</script>
<script type="text/javascript">
	 $(function () {
            //添加视频
            $("#fileSelecter").selectUpload({
                maxFileSize: 1024 * 1024 * 1024 * 2, //允许上传的最大值,单位是字节
                addFiles: function (data) { //添加文件时的回调
                    $("#videoId").html(data.fileName);
                    $("#videoProgress").html("0");
                    $("#videoSpeed").html("0");
                    $("#videoStatus").html("等待上传");
                },
                errorCallback: function (data) { //添加文件时发生错误的回调
                    alert("错误码:" + data.code + ";错误消息:" + data.msg);
                }
            });

            //开始上传
            $("#uploadBtn").upload({
                  //initUrl: "/html5UploadInit.php",//初始化上传地址
                initUrl: "{:url('upload_video')}?action=lecloud_upload_https&pid={$pid}&bid={$bid}&id={$id}",//初始化上传地址
                uploadProgress: function (progress, rate) { //进度回调
                    $("#videoProgress").html(progress);
                    $("#videoSpeed").html(rate);
                    $("#videoStatus").html("上传中");
                },
                finishCallback: function (data) { //上传完成回调
                    $("#videoProgress").html("100%");
                    $("#videoSpeed").html("0");
                    $("#videoStatus").html("已上传");
                },
                errorCallback: function (data) { //上传错误回调
                    $("#videoProgress").html("0");
                    $("#videoSpeed").html("0");
                    $("#videoStatus").html("上传错误!错误码:" + data.code + ";错误消息:" + data.msg);
                }
            });
        });
</script>
    
</body>
</html>

initUrl: "{:url('upload_video')}?action=lecloud_upload_https&pid={$pid}&bid={$bid}&id={$id}",//初始化上传地址

2、{:url('upload_video')}控制器代码

							$sdkModel = model('LetvCloudV1');
							$video_name = trim($_GET['video_name']);
							if (empty($video_name)) {
							    $video_name = '乐视云视频';
							}
							$client_ip = get_client_ip();
							$file_size = isset($_GET['file_size']) ? intval($_GET['file_size']) : 0;
							$uploadtype = isset($_GET['uploadtype']) ? intval($_GET['uploadtype']) : 0;
							if (isset($_GET['token']) && !empty(trim($_GET['token']))) {
								$token = trim($_GET['token']);
								echo $sdkModel -> videoUploadResume($token,$uploadtype);die;
							}else{
								echo $sdkModel -> videoUploadInit($video_name, $client_ip, $file_size,$uploadtype);die;
							}

3、模型代码

<?php
namespace app\admin\model;
use think\Model;
use think\Db;
class LetvCloudV1 extends Model
{
		public $user_unique='4xxxxx7';
		public $secret_key='dc9xxxxxxxxxxxxxxxf22d4';
		public  $restUrl= 'http://api.letvcloud.com/open.php';
		public  $format = 'json';	
		//public  $format = 'jsonp';	
		protected $apiVersion = '2.0';		
        
        /**
         * 视频上传初始化
         * @param  string $video_name 视频名称
         * @param  string $client_ip  用户ip地址
         * @param  int $file_size  文件大小,单位为字节
		 * @param  int $uploadtype  上传分片模式
         * @return string
         */
        public function videoUploadInit($video_name,$client_ip,$file_size,$uploadtype){
        	$api = 'video.upload.init';
        	$params['video_name'] = $video_name;
        	if(!empty($client_ip)){
        		$params['client_ip'] = $client_ip; 
        	}
        	if(!empty($file_size)){
        		$params['file_size'] = $file_size;
        	}
        	$params['uploadtype'] = $uploadtype;
        	return self::httpCall($api, $params);
        }       
        	
        /**
         * 视频上传 (web方式)
         * @param  string $video_file 文件绝对路径
         * @param  string $upload_url 视频上传地址,视频上传时提交地址
         * @return string
         */
        public function videoUpload($video_file,$upload_url){
       		$postFields['video_file'] = "@".$video_file;
       		return $this->curl($upload_url,$postFields);        	
        }
        
        /**
         * 视频断点续传
         * @param  string $token 视频上传标识
		 * @param  int $uploadtype  上传分片模式
         * @return string
         */
        public function videoUploadResume($token,$uploadtype){
        	$api = 'video.upload.resume';
        	$params['token'] = $token;
			$params['uploadtype'] = $uploadtype;
        	return self::httpCall($api, $params);
        }
        
        /**
         * 视频上传(Flash方式)
         * @param  string $video_name 视频名称
         * @param  string $js_callback Javascript回调函数,视频上传完毕后调用
         * @param  int $flash_width Flash宽度,默认值为600
         * @param  int $flash_height Flash高度,默认值为450
         * @param  string $client_ip 用户IP地址
         * @return string
         */
        public function videoUploadFlash($video_name,$js_callback='',$flash_width=600,$flash_height=450,$client_ip=''){
        	$api = 'video.upload.flash';
        	$params['video_name'] = $video_name;
        	if(!empty($js_callback)){
        		$params['js_callback'] = $js_callback;
        	}
        	$params['flash_width'] = $flash_width;
        	$params['flash_height'] = $flash_height;
        	if(!empty($client_ip)){
        		$params['client_ip'] = $client_ip;
        	}
        	return self::httpCall($api, $params);        	
        }
        
        /**
         * 视频信息更新
         * @param  int $video_id 视频ID
         * @param  string $video_name 视频名称
         * @param  string $video_desc 视频简介
         * @param  string $tag 标签
         * @param  int $is_pay 视频是否收费:0表示不收费;1表示收费(收费视频播放时会进行用户鉴权,请不要随便设置)
         * @return string
         */
        public function videoUpdate($video_id,$video_name='',$video_desc='',$tag='',$is_pay=0){
        	$api = 'video.update';
        	$params['video_id'] = $video_id;
        	if(!empty($video_name)){
        		$params['video_name'] = $video_name;
        	}        	
        	if(!empty($video_desc)){
        		$params['video_desc'] = $video_desc;
        	}
        	if(!empty($tag)){
        		$params['tag'] = $tag;
        	}
        	if(!empty($is_pay)){
        		$params['is_pay'] = $is_pay;
        	}
        	return self::httpCall($api, $params);
        }
        
        /**
         * 获取视频列表
         * @param  int $index 开始页索引,默认值为1
         * @param  int $size 分页大小,默认值为10,最大值为100
         * @param  const $status 视频状态:ALL表示全部;PLAY_OK表示可以正常播放;FAILED表示处理失败;WAIT表示正在处理过程中。默认值为ALL
         * @return string
         */
        public function videoList($index=1,$size=10,$status=ALL){
        	$api = 'video.list';
        	$params['index'] = $index;
        	$params['size'] = $size;
        	$params['status'] = $status;
        	return self::httpCall($api, $params);
        }
        
		/**
		 * 获取单个视频信息
		 * @param  int $video_id 视频id
		 * @return string
		 */
        public function videoGet($video_id){
        	$api = 'video.get';
        	$params = array('video_id'=>$video_id);
        	return self::httpCall($api, $params);
        }
        
        /**
         * 删除视频
         * @param  int $video_id 视频ID
         * @return string
         */
        public function videoDel($video_id){
        	$api = 'video.del';
        	$params['video_id'] = $video_id;
        	return self::httpCall($api, $params);
        }
        
        /**
         * 批量删除视频
         * @param  string $video_id_list 视频ID列表,使用符号-作为间隔符,每次最多操作50条记录
         * @return string
         */
        public function videoDelBatch($video_id_list){
        	$api = 'video.del.batch';
        	$params['video_id_list'] = $video_id_list;
        	return self::httpCall($api, $params);
        }
        
        /**
         * 视频暂停
         * @param  int $video_id 视频ID
         * @return string
         */
        public function videoPause($video_id){
        	$api = 'video.pause';
        	$params['video_id'] = $video_id;
        	return self::httpCall($api, $params);
        }
        
        /**
         * 视频恢复
         * @param  int $video_id 视频ID
         * @return string
         */
        public function videoRestore($video_id){
        	$api = 'video.restore';
        	$params['video_id'] = $video_id;
        	return self::httpCall($api, $params);
        }
        
        /**
         * 获取视频截图
         * @param  int $video_id 视频ID
         * @param  string $size 截图尺寸,每种尺寸各有8张图。
         * @return string
         */
        public function imageGet($video_id,$size){
        	$api = 'image.get';
        	$params['video_id'] = $video_id;
        	$params['size'] = $size;
        	return self::httpCall($api, $params);
        }
        
        /**
         * 视频小时数据
         * @param  string $date 日期,格式为:yyyy-mm-dd
         * @param  int $hour 小时,0-23之间
         * @param  int $video_id 视频ID
         * @param  int $index 开始页索引,默认值为1
         * @param  int $size 分页大小,默认值为10,最大值为100
         * @return string
         */
        public function dataVideoHour($date,$hour=null,$video_id=null,$index=1,$size=10){
        	$api = 'data.video.hour';
        	$params['date'] = $date;
        	if($hour != null){
        		$params['hour'] = $hour;
        	}
        	if($video_id != null){
        		$params['video_id'] = $video_id;
        	}
        	$params['index'] = $index;
        	$params['size'] = $size;
        	return self::httpCall($api, $params);
        }
        
        /**
         * 视频天数据
         * @param  string $start_date 开始日期,格式为:yyyy-mm-dd 
         * @param  string $end_date 结束日期,格式为:yyyy-mm-dd
         * @param  int $video_id 视频ID,不输入该参数将返回所有视频的数据
         * @param  int $index 开始页索引,默认值为1
         * @param  int $size 分页大小,默认值为10,最大值为100
         * @return string
         */
        public function dataVideoDate($start_date,$end_date,$video_id=null,$index=1,$size=10){
        	$api = 'data.video.date';
        	$params['start_date'] = $start_date;
        	$params['end_date'] = $end_date;
        	if($video_id != null){
        		$params['video_id'] = $video_id;
        	}
        	$params['index'] = $index;
        	$params['size'] = $size;
        	return self::httpCall($api, $params);
        }
        
        /**
         * 所有数据
         * @param  string $start_date 开始日期,格式为:yyyy-mm-dd
         * @param  string $end_date 结束日期,格式为:yyyy-mm-dd
         * @param  int $index 开始页索引,默认值为1
         * @param  int $size 分页大小,默认值为10,最大值为100
         * @return string
         */
        public function dataTotalDate($start_date,$end_date,$index=1,$size=10){
        	$api = 'data.total.date';
        	$params['start_date'] = $start_date;
        	$params['end_date'] = $end_date;
        	$params['index'] = $index;
        	$params['size'] = $size;
        	return self::httpCall($api, $params);
        }
        
        /**
         * 获取视频播放接口
         * @param string $uu 用户唯一标识码,由乐视网统一分配并提供
         * @param string $vu 视频唯一标识码
         * @param string $type 接口类型:url表示播放URL地址;js表示JavaScript代码;flash表示视频地址;html表示HTML代码
         * @param string $pu 播放器唯一标识码
         * @param int $auto_play 是否自动播放:1表示自动播放;0表示不自动播放。默认值由双方事先约定
         * @param int $width 播放器宽度
         * @param int $height 播放器高度 
         * @return string
         */
        public function videoGetPlayinterface($uu,$vu,$type,$pu="",$auto_play=null,$width=0,$height=0){
        	$args = array();
        	$args['uu'] = $uu;
        	$args['vu'] = $vu;
        	if(!empty($pu)){
        		$args['pu'] = $pu;
        	}
        	if($auto_play != null){
        		$args['auto_play'] = $auto_play;
        	}
        	if($width>0){
        		$args['width'] = $width;
        	}
        	if($height>0){
        		$args['height'] = $height;
        	}
        	$queryString = http_build_query($args);
        	$jsonString = json_encode($args);
        	if($type == "url"){
        		$res = "http://yuntv.letv.com/bcloud.html?".$queryString; 
        	}elseif ($type == "js"){
        		$res = '<script type="text/javascript">var letvcloud_player_conf = '.$jsonString.';</script><script type="text/javascript" src="http://yuntv.letv.com/bcloud.js"></script>';
        	}elseif ($type == "flash"){
        		$res = "http://yuntv.letv.com/bcloud.swf?".$queryString;
        	}elseif ($type == "html"){
        		$res = '<embed src="http://yuntv.letv.com/bcloud.swf" allowFullScreen="true" quality="high" width="800" height="450" align="middle" allowScriptAccess="always" flashvars="'.$queryString.'" type="application/x-shockwave-flash"></embed>';
        	}
        	return $res;
        }
        
		/** 
		 * 构造云视频Sign
		 * @param array $params 业务参数
		 * @return string
		 */
		public function generateSign($params){
			ksort($params);
			$keyStr = '';
			foreach($params as $key => $value){
				$keyStr .= $key.$value;
			}
			$keyStr .= $this->secret_key;
			$key = md5($keyStr);
			return $key;
		}
		
	    /** 
	     * 发送http请求
	     * @param $url 请求地址
	     * @param $postFields HTTP方法为POST时的请求参数
	     * @return string HTTP请求相应结果
	     */
		public function curl($url, $postFields = null) {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_FAILONERROR, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//			//https 请求
			if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
			}
	
			if (is_array($postFields) && 0 < count($postFields))
			{
				$postBodyString = "";
				$postMultipart = false;
				foreach ($postFields as $k => $v)
				{
					if("@" != substr($v, 0, 1))//判断是不是文件上传
					{	
						$postBodyString .= "$k=" . urlencode($v) . "&"; 
					}
					else//文件上传用multipart/form-data,否则用www-form-urlencoded
					{
						$postMultipart = true;
					}
				}
				unset($k, $v);
				curl_setopt($ch, CURLOPT_POST, true);
				if ($postMultipart)
				{
					curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
				}
				else
				{
					curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
				}
			}
			$reponse = curl_exec($ch);
			
			if (curl_errno($ch))
			{
				throw new Exception(curl_error($ch),0);
			}
			else
			{
				$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
				if (200 !== $httpStatusCode)
				{
					throw new Exception($reponse,$httpStatusCode);
				}
			}
			curl_close($ch);
			return $reponse;
		}
		
	    /**
	     * 获取HTTP请求结果
	     * @param $api API名称 , 如:video.get
	     * @param $apiParams API业务参数
	     * @return string
	     */
	    public function httpCall($api,$apiParams){
	    	//组装系统参数
	    	$sysParams['user_unique'] = $this->user_unique;
			//$sysParams['timestamp'] = time();	
			$sysParams['timestamp'] = "1369300735578";	
			$sysParams['ver'] = $this->apiVersion;		
			$sysParams['format'] = $this->format;
			$sysParams["api"] = $api;
	    	//参数集合=系统参数+业务参数
	    	$params = array_merge($sysParams, $apiParams);
	    	//构造请求URL
	    	$resurl = '';
	    	$resurl .= $this->restUrl;	    	
	    	//签名	
			$params['sign'] = $this->generateSign($params);		
			//参数放入GET请求串
			foreach($params as $key=>$v)
			{
				if(!strpos($resurl, '?'))
				{
					$resurl .= "?{$key}=" . urlencode($v);
				}
				else
				{
					$resurl .="&{$key}=" . urlencode($v);
				}
			}
	    	//发起HTTP请求
	    	//dump($resurl);die;
			$respObj = $this->curl($resurl);
//			$respObj =file_get_contents($resurl);
			return $respObj;
	    }
}

4、各js文件引用

    <script type="text/javascript" src="__STATIC__/admin/lecloud//jquery.form.js"></script>
    <script type="text/javascript" src="__STATIC__/admin/lecloud//formUpload.js"></script>

重点是formUpload.js代码

/**
 * Created by 郝少禅
 * Email:sxchying@126.com
 * QQ:490746237
 */
window.formUpload = (function () {
    function formUpload() {
    }
    //是否可以上传
    var isNotUpload = false;
    var selectFileOption = {};
    var uploadOption = {};
    (function () {
        //绑定选择文件按钮
        (function ($) {
            var defaults = {
                maxFileSize: 1024 * 1024 * 1024,
                addFiles: function (fileName) {

                },
                errorCallback: function (data) {

                }
            };
            $.fn.selectUpload = function (options) {
                selectFileOption = $.extend(defaults, options || {});
                return this.each(function () {
                    $(this).click(fileOperation.fileSelect);
                });
            };
        })(jQuery);
        //绑定上传按钮
        (function ($) {
            var defaults = {
                initUrl: "",
                uploadProgress: function (data) {

                },
                finishCallback: function (data) {

                },
                errorCallback: function (data) {

                }
            };
            $.fn.upload = function (options) {
                uploadOption = $.extend(defaults, options || {});
                return this.each(function () {
                    $(this).click(function () {
                        if (isNotUpload == false) {
                            uploadOption.errorCallback({ code: 131, msg: "未选择文件" });
                        } else {
                            videoUpload.tryUpload();
                        }
                    });
                });
            };
        })(jQuery);
    })();
    var fileOperation = (function () {
        function fileOperation() {
        }
        var fileTypes = "wmv|avi|dat|asf|rm|rmvb|ram|mpg|mpeg|mp4|mov|m4v|mkv|flv|vob|qt|divx|cpk|fli|flc|mod|dvix|dv|ts";
        var getFileType = function (file) {
            return file.name.split(".").pop();
        };
        var showFileList = function (e) {
            if (e.target.files.length > 1) {
                selectFileOption.errorCallback({ code: 100, msg: "只能选择一个文件" });
            } else {
                var file = e.target.files[0];
                var fType = getFileType(file);
                if (file.size > selectFileOption.maxFileSize) {
                    selectFileOption.errorCallback({ code: 101, msg: "文件过大" });
                } else if (eval("/" + fileTypes + "$/i").test(fType) == false) {
                    selectFileOption.errorCallback({ code: 102, msg: "不支持此文件类型" });
                } else {
                    selectFileOption.addFiles({code:0,fileName:file.name});
                    fileOperation.selectFile = file;
                    isNotUpload = true;
                }
            }
        };
        fileOperation.selectFile = {};
        fileOperation.fileSelect = function (e) {
            var form = document.getElementById("form_Hsc");
            if (!form) {
                form = document.createElement("form");
                $("body").append(form);
                form.setAttribute("id", "form_Hsc");
                form.setAttribute("name", "form_Hsc")
                form.setAttribute("enctype", "multipart/form-data")
            }
            var inpfile = document.getElementById("fileUploadId_Hsc");
            if (inpfile) {
                inpfile.click && e.target != inpfile && inpfile.click();
            } else {
                inpfile = document.createElement("input");
                $("#form_Hsc").append(inpfile);
                inpfile.setAttribute("id", "fileUploadId_Hsc");
                inpfile.setAttribute("name", "fileUploadId_Hsc")
                inpfile.setAttribute("type", "file");
                inpfile.style.display = "none";
                inpfile.addEventListener('change',showFileList, !1);
                inpfile.click && e.target != inpfile && inpfile.click();
            }
        };
        return fileOperation;
    })();
    var videoUpload = (function () {
        function videoUpload() {
        }
        var streamUpload = function (url) {
            var file = fileOperation.selectFile;
            var inittime = (new Date()).getTime();
            var ajax_option = {
                url: url,
                type: "post",
//                dataType: "jsonp",
                dataType: "json",
                success: function (data) {
                    if (data.code == 0) {
                        uploadOption.finishCallback({ code: data.code, msg: data.message });
                        isNotUpload = false;
                    } else {
                        uploadOption.errorCallback({ code: data.code, msg: data.message });
                        isNotUpload = false;
                    }
                },
                error: function (data) {
                    isNotUpload = false;
                    uploadOption.errorCallback({ code: data.code, msg: data.message });
                },
                uploadProgress: function (event, loaded, total, percentComplete) {
                    var delttime = ((new Date()).getTime() - inittime) / 1000;
                    var uploadSize = parseInt(percentComplete + "") * file.size / 100;
                    var rate = uploadSize / delttime;
                    rate = rate / 1024;
                    rate = rate > 1024 ? (((rate / 1024 * 10) >> 0) / 10).toFixed(1) + "M/s" : (((rate * 10) >> 0) / 10).toFixed(1) + "K/s";
                    if (percentComplete == 100) {
                        percentComplete = 99;
                    }
                    uploadOption.uploadProgress(percentComplete + "%", rate);
                },
                timeout: 60000000
            }
            $("#form_Hsc").ajaxSubmit(ajax_option);
        };
        videoUpload.tryUpload = function () {
            var file = fileOperation.selectFile;
            $.ajax({
                url: uploadOption.initUrl + "?video_name=" + encodeURIComponent(file.name) + "&uploadtype=0&file_size=" + file.size,
                type: 'get',
                //dataType: "jsonp",
                dataType: "json",
                success: function (data) {
                	
					var protocolStr = document.location.protocol;
						if(protocolStr == "http:"){
						   //console.log("protocol = " + protocolStr);
						   var url = data.data.upload_url;
						}else if(protocolStr == "https:"){
							var url = data.data.upload_https_url;
						  // console.log("protocol = " + protocolStr);
						}
 
                    streamUpload(url);
                }
            });
        };
        return videoUpload;
    })();
    return formUpload;
})();

 

二、video_upload_demo_v2.zip

一样子的原理

 

主要修改Gandalf.js

/
//Gandalf : software define storage upload sdk
/

var SliceState = {"failed" : -1, "ready" : 0, "waiting" : 1, "uploading" : 2, "success" : 3};
var CallbackState = {"failed" : 800, "lost" : 801, "giveup" : 802, "success" : 0};

//start upload
(function () {

    //callback array
    window.callbacks = [];
    //file upload array
    window.producers = [];
    //upload file fucntion
    window.LCUploader = function (obj) {

        var cb = new Object();
        cb.uploadUrl = obj.uploadUrl;
        cb.file = obj.file;
        cb.uc1 = obj.uc1;
        cb.uc2 = obj.uc2;
        cb.fileKey = obj.fileKey;
        cb.uploadType = 1;
        cb.load = obj.load;
        cb.progress = obj.progress;
        cb.error = obj.error;
        cb.abort = obj.abort;
        window.callbacks.push(cb);

        var pr = new window.Producer();
        window.producers.push(pr);
        var simpleAjax = new window.simpleA();

        pr.tryProduce(cb.uploadUrl, cb.file, cb, simpleAjax);
		 
    }

    window.SDSAbort = function (fileKey) {
        for (var i = producers.length - 1; i >= 0; i--) {
            if (producers[i].uploadOption.fileKey == fileKey) {
                producers[i].xhrAbort();
            }
        };
    }

})();

//slice upload
(function () {
    window.Consumer = function () {

        this.xhr = null;
        this.sdsParent = null;

        //SliceInfo: uploadUrl, filename, totalSize, sliceIndex, sliceSize, sliceData
        this.sliceUpload = function (sliceInfo, _parent) {

            if (!_parent)
                return;

            this.sdsParent = _parent;
            this.sdsParent.sliceState[sliceInfo.sliceIndex] = SliceState.uploading;

            this.xhr = new XMLHttpRequest();
            this.xhr.upload.addEventListener("progress", function (e) { _parent.progress(e, sliceInfo.sliceIndex, this.sdsParent) }, false);
            this.xhr.addEventListener("loadstart", function (e) { _parent.loadstart(e, sliceInfo.sliceIndex, this.sdsParent) }, false);
            this.xhr.addEventListener("error", function (e) { _parent.error(e, sliceInfo.sliceIndex, this.sdsParent) }, false);
            this.xhr.addEventListener("abort", function (e) { _parent.abort(e, sliceInfo.sliceInfo.sliceIndex, this.sdsParent) }, false);
            this.xhr.addEventListener("load", function (e) { _parent.load(e, sliceInfo.sliceIndex, this.sdsParent) }, false);

            var start = sliceInfo.sliceIndex * sliceInfo.sliceSize;
            var content = start == -1 ? "bytes *" : "bytes " + (start + 1) + "-" + (start + sliceInfo.sliceData.size) + "/" + sliceInfo.totalSize;
            
            this.xhr.open("POST", sliceInfo.uploadUrl, true)
            this.xhr.setRequestHeader("Pragma", "letv_LCUploader_1.0");
            this.xhr.setRequestHeader("X_FILENAME", encodeURI(sliceInfo.filename));
            this.xhr.setRequestHeader("Content-Range", content);

            this.xhr.send(sliceInfo.sliceData);
        };

        this.xhrAbort = function () {
            this.xhr && this.xhr.abort();
        }
    };
})();


//producer upload
(function () {
    window.Producer = function () {
        
        this.currentFile = {};
        this.sliceCount = 0;  //slice count of file
        this.sliceState = []; //slice status : -n -> failed count, 0 -> waiting upload, 1 -> upload success
        this.slicePost = []; //slice uploaded size already
        this.sliceSize = 10485760;  //10M
        this.sliceStack = {};

        this.xhr = null;
        this.uploadOption = {};

        this.uploadUrl = "";

        this.concurrentCount = 1;
        this.failedCount = 0;
        this.maxFailedCount = 20;
        this.Consumers = [];

        this.format = function () {
            var b, a = arguments,
                d = a[0] || {},
                f = 1,
                e = a.length;
            if (!e) return null;
            for (e === f && (d = this, --f) ; f < e; f++)
                if (null != (b = a[f]))
                    for (var c in b) d[c] = b[c];
            return d
        };

        this.evalTo = function (string) {
            try {
                return (new Function("return " + string))();
            } catch (e) {
                console && console.log("Error: " + string);
            }
        };

        this.tryProduce = function(initUrl, file, option, simpleAjax) {

            var data = { videoname: encodeURIComponent(file.name) }
            var _simpleAjax = simpleAjax;
            var argument = this.format(data, {
                client: "html5", 
                uploadtype: option.uploadType,
                file_size: file.size,
                t: (new Date).getTime(),
                uc1: option.uc1,
                uc2: option.uc2
            })

            var _self = this;

            if (window.html5UploadCookie.getItem(option.fileKey)) {
                argument = { token: window.html5UploadCookie.getItem(option.fileKey), uploadtype: option.uploadType };
            }

            simpleAjax.get(initUrl, argument, function (reqData) {
				 
                try {
                    var data = eval("(" + reqData + ")");
                } catch (e) {
                    var data = { code: 999 };
                } 
                if (data.code == 0) {
                    var uploadPos = data.data.upload_size || 0;
					var protocolStr = document.location.protocol;
						if(protocolStr == "http:"){
                                           var url = data.data.upload_https_url.substr(0, data.data.upload_https_url.length - 10);
						}else if(protocolStr == "https:"){
                                           var url = data.data.upload_https_url.substr(0, data.data.upload_https_url.length - 10);
						}
                   // var url = data.data.upload_url.substr(0, data.data.upload_url.length - 10);
				
					
                    _self.tryUpload(url, file, uploadPos, option);

                } else {
                    if (this.option.init) {
                        option.init(data);
                    }
                }
            });
        };

        this.tryUpload = function (url, file, transferedsize, option) {

            this.uploadUrl = url;
            this.currentFile = file;
            this.uploadOption = option;
            this.sliceStack.transferedSize = transferedsize < 0 ? 0 : transferedsize;
            this.sliceStack.startPosition = this.sliceStack.transferedSize;
            this.sliceStack.initTime = 0;

            this.sliceCount = Math.ceil(file.size / this.sliceSize);  //slice count
            var slicePos = Math.floor(this.sliceStack.startPosition / this.sliceSize); //start upload position

            //resume upload
            for (var index = 0; index < slicePos; index++) {
                this.sliceState[index] = SliceState.success;
                this.slicePost[index] = this.sliceSize;
            }

            for (var index = slicePos; index < this.sliceCount; index++) {
                this.sliceState[index] = SliceState.ready;
                this.slicePost[index] = 0;
            }
          
            var runCount = Math.min(this.concurrentCount, this.sliceCount - 1);
            runCount = Math.max(runCount, 1);
            for (var index = 0; index < runCount; index++) {

              this.consumerUpload(slicePos + index);
            }

        };

        this.consumerUpload = function(sliceIndex) {
            //SliceInfo: uploadUrl, filename, totalSize, sliceIndex, sliceSize, sliceData

            var consumer = new window.Consumer();
            this.Consumers.push(consumer);

            sliceInfo = {};
            sliceInfo.uploadUrl = this.uploadUrl;
            sliceInfo.filename = this.currentFile.name;
            sliceInfo.totalSize = this.currentFile.size;
            sliceInfo.sliceIndex = sliceIndex;
            sliceInfo.sliceSize = this.sliceSize;
            start = sliceInfo.sliceIndex * sliceInfo.sliceSize;
            sliceInfo.sliceData = this.fileSlice(this.currentFile, start);

            consumer.sliceUpload(sliceInfo, this);
        };

        this.fileSlice = function (file, start) {

            var blob;
            start = start || 0;
            var range = Math.min(file.size, start + this.sliceSize);
            if (start != -1) {
                if (file.slice) {
                    blob = file.slice(start, range);
                } else if (file.webkitSlice) {
                    blob = file.webkitSlice(start, range);
                } else if (file.mozSlice) {
                    blob = file.mozSlice(start, range);
                } else {
                    blob = file;
                }
            } else {
                return null;
            }
            return blob;
        };

        this.load = function (e, sliceIndex, _self) {

          //upload failed , server return stauts != 200
          var res = this.evalTo(e.target.responseText);
          if (!res.totalsize && res.status != '200') {
            if (this.uploadOption.error) {
                this.uploadOption.error(CallbackState.failed, e);
            }
            window.html5UploadCookie.removeItem(this.uploadOption.fileKey);
            this.xhrAbort();
            return;
          }

          var tokenUrl = this.uploadUrl.split('token').pop();
          var videoToken = tokenUrl.substr(1, tokenUrl.length - 1).split('&')[0];
          window.html5UploadCookie.setItem(this.uploadOption.fileKey, videoToken, 30);

          this.sliceStack.starttime = (new Date()).getTime();
          if (res.transferedsize && res.transferedsize == res.totalsize) {
            if (this.uploadOption.load) {
                window.html5UploadCookie.removeItem(this.uploadOption.fileKey);
                this.uploadOption.load(CallbackState.success, e);
                return;
            }
          }

          this.sliceState[sliceIndex] = SliceState.success;

          //file send complete
          //if (sliceIndex == this.sliceCount - 1) {
            //this.uploadOption.load(0, e);
            //return;
          //}

          //check ready to upload slice
          for (var index = sliceIndex + 1; index < this.sliceCount - 1; index++) {

            if (this.sliceState[index] == SliceState.ready) {
                this.consumerUpload(index);                
              return;
            }
          }

          var flag = true;
          for (var index = 0; index < this.sliceCount - 1; index++) {
            if (flag && this.sliceState[index] != SliceState.success) {
              flag = false;
              break;
            }
          }

          //send last slice
          if (flag) {
                this.consumerUpload(this.sliceCount - 1);
            }
        };

        this.loadstart = function (e, sliceIndex, _self) {
          this.sliceStack.initTime = (new Date()).getTime(); 
        };

        this.progress = function (e, sliceIndex, _self) {
          //
          this.slicePost[sliceIndex] = e.loaded;

          var transferedSize = 0;
          for (var index = 0; index < this.slicePost.length; index++) {
            transferedSize += this.slicePost[index];
          }

          this.sliceStack.transferedSize = transferedSize;

          var pc = parseInt(this.sliceStack.transferedSize / this.currentFile.size * 100);
          var deltaTime = ((new Date()).getTime() - (this.sliceStack.startTime || this.sliceStack.initTime)) / 1000;
          var rate = e.loaded / deltaTime;
          rate = rate / 1024;
          rate = rate > 1024 ? (((rate / 1024 * 10) >> 0) / 10).toFixed(1) + "M/s" : (((rate * 10) >> 0) / 10).toFixed(1) + "K/s";

          //delete file while upload file
          if (isNaN(pc)) {
            this.uploadOption.progress(CallbackState.lost, e);
            this.xhrAbort();
          } else if (this.uploadOption.progress) {
            this.uploadOption.progress(CallbackState.success, { progress: pc + "%", speed: rate, file: this.currentFile });
          }
        };

        this.error = function (e, sliceIndex, _self) {
          if (this.failedCount > this.maxFailedCount) {
            if (this.uploadOption.error) {
                this.uploadOption.error(CallbackState.failed, e);
            }
            this.xhrAbort();
          } else {
            this.failedCount += 1;
            this.consumerUpload(sliceIndex);
          }
        };

        this.abort = function (e, sliceIndex, _self) {
          if (this.uploadOption.abort) {
                this.uploadOption.abort(e);
            }
        };

        this.xhrAbort = function () {
            for (var index = 0; index < this.Consumers.length; index++) {
                if (this.Consumers[index]) {
                    this.Consumers[index].xhrAbort();
                }
            }
        };
    };
})();


//encapsulate ajax
(function () {
    function Glib() {
        this.JsonToParam = function (json) {
            var s = { a: 1, b: 2 }
            var arr = [];
            for (var p in json) {
                arr.push(p + "=" + json[p]);
            }
            return arr.join('&');
        }
    };

    function Ajax() {
        this.GXHR = null;
        this.CALLBACK = function () { };
        Glib.apply(this)
    };

    Ajax.prototype = {
        reviveXHR: function () {
            if (this.GXHR) { return }
            var _XHR,
            _msieXHR = [
            'Msxml2.XMLHTTP.5.0',
            'Msxml2.XMLHTTP.4.0',
            'Msxml2.XMLHTTP.3.0',
            'Msxml2.XMLHTTP',
            'Microsoft.XMLHTTP'
            ];
            for (var i = 0, l = _msieXHR.length; i < l; i++) {
                try {
                    if (_XHR = new ActiveXObject(_msieXHR[i])) break;
                } catch (e) {
                    _XHR = null;
                }
            }

            if (_XHR || (_XHR = new XMLHttpRequest, typeof XMLHttpRequest != 'undefined')) {
                return _XHR;
            }
            if (!_XHR) throw new Error("connection object not define.");
        },
        scope: function (fn, scope) {
            return function () { return fn.apply(scope) }
        },
        fmtFn: function (fn) {
            if (typeof fn == 'function') {
                this.CALLBACK = fn;
            }
            var _callback = this.CALLBACK || new Function;
			 
            return _callback;
        },

        stateHandle: function () {
            var _self = this.GXHR;
            if (_self.readyState == 2) {
            } else if (_self.readyState == 4) {
                if (_self.status == 200) {
                    this.CALLBACK(_self.responseText);
                }
            }

        },
        fmtParam: function (data) {
            var urlParam = null;
            if (typeof data != 'string' && typeof data == 'object') {
                urlParam = this.JsonToParam(data);
            }
            return urlParam || data;
        },
        request: function (url, data, callback, method) {
            method = method || "GET";
            if (method == 'GET') {
                if (url.indexOf('?') != -1)
                    url += "&";
                else
                    url += "?";
                url += this.fmtParam(data);
            }
            var _self = this;
            _self.CALLBACK = this.fmtFn(callback);

            _self.GXHR = _self.GXHR || _self.reviveXHR();
            _self.GXHR.onreadystatechange = _self.scope(_self.stateHandle, _self);
            _self.GXHR.open(method, url, true);
            _self.GXHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            _self.GXHR.send(_self.fmtParam(data) || null);
			 
        },

        get: function (url, data, callback) {
            return this.request(url, data, callback, "GET");
        },
        post: function (url, data, callback) {
            var url = url + '?uc1=5&uc2=8';
            return this.request(url, data, callback, 'POST');

        },
        getJSON: function (url, data, fn) {
            var oldScript = document.getElementById(url);
            if (oldScript) {
                oldScript.setAttribute("src", url);
                return;
            }
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement("script");
            script.setAttribute('type', 'text/javascript');
            script.setAttribute('src', url);
            script.setAttribute('id', url);
            head.appendChild(script);
            window['callback'] = function (data) {
                try {
                    fn && fn(data);
                } catch (e) { }
            };
            script.onload = script.onreadystatechange = function () {
                if ((!this.readyState || this.readyState === "complete" || this.readyState === "loaded")) {

                    script.onload = script.onreadystatechange = null; //IE内存溢出
                    if (head && script.parentNode) {
                        head.removeChild(script);
                    }
                }
            };
        }
    }
    window.simpleA = Ajax;
    window.Ajax = new Ajax;
})();

//cookie save token resume
(function () {
    window.html5UploadCookie = {
        setItem: function (key, value, expiresDays) {
            var date = new Date();
            date.setTime(date.getTime() + expiresDays * 24 * 3600 * 1000);
            document.cookie = key + "=" + value + "; expires=" + date.toGMTString();
        },
        getItem: function (key) {
            var strCookie = document.cookie;
            var arrCookie = strCookie.split("; ");
            for (var i = 0; i < arrCookie.length; i++) {

                var arr = arrCookie[i].split("=");
                if (arr[0] == key) {
                    return arr[1];
                }
                if (i == arrCookie.length - 1) {
                    return false;
                }
            }
        },
        removeItem: function (key) {
            window.html5UploadCookie.setItem(key, "", -1);
        }
    };
})();


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
机器学习是一种人工智能(AI)的子领域,致力于研究如何利用数据和算法让计算机系统具备学习能力,从而能够自动地完成特定任务或者改进自身性能。机器学习的核心思想是让计算机系统通过学习数据中的模式和规律来实现目标,而不需要显式地编程。 机器学习应用非常广泛,包括但不限于以下领域: 图像识别和计算机视觉: 机器学习在图像识别、目标检测、人脸识别、图像分割等方面有着广泛的应用。例如,通过深度学习技术,可以训练神经网络来识别图像中的对象、人脸或者场景,用于智能监控、自动驾驶、医学影像分析等领域。 自然语言处理: 机器学习在自然语言处理领域有着重要的应用,包括文本分类、情感分析、机器翻译、语音识别等。例如,通过深度学习模型,可以训练神经网络来理解和生成自然语言,用于智能客服、智能助手、机器翻译等场景。 推荐系统: 推荐系统利用机器学习算法分析用户的行为和偏好,为用户推荐个性化的产品或服务。例如,电商网站可以利用机器学习算法分析用户的购买历史和浏览行为,向用户推荐感兴趣的商品。 预测和预测分析: 机器学习可以用于预测未来事件的发生概率或者趋势。例如,金融领域可以利用机器学习算法进行股票价格预测、信用评分、欺诈检测等。 医疗诊断和生物信息学: 机器学习在医疗诊断、药物研发、基因组学等领域有着重要的应用。例如,可以利用机器学习算法分析医学影像数据进行疾病诊断,或者利用机器学习算法分析基因数据进行疾病风险预测。 智能交通和物联网: 机器学习可以应用于智能交通系统、智能城市管理和物联网等领域。例如,可以利用机器学习算法分析交通数据优化交通流量,或者利用机器学习算法分析传感器数据监测设备状态。 以上仅是机器学习应用的一部分,随着机器学习技术的不断发展和应用场景的不断拓展,机器学习在各个领域都有着重要的应用价值,并且正在改变我们的生活和工作方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值