1. 程式人生 > >使用愛奇藝開放平臺上傳視頻

使用愛奇藝開放平臺上傳視頻

ext 問題 isp tool shu for 文件 video ons

一、問題背景:

在最近的一個項目中,需要有一個上傳視頻的功能,原先使用的優酷開放平臺,但是由於很久沒有維護了,導致賬號過期了,且優酷開放平臺在17年三月份之後,就暫停新應用的創建和生成新的應用,所以重新選用了愛奇藝開放平臺。

二、使用步驟

(說明:申請賬號,創建應用和審核,請參考官方的文檔,我在這裏就不做詳細的說明了,這裏直接上代碼。不過我也是第一次使用這個愛奇藝的開放平臺,所以可能會有錯誤,但是功能是可以實現的)

引用sdkbase_min.js

HTML:

<div class="container">
				<form  class="well form-horizontal"  name="video-upload">
					<fieldset>
						<div class="control-group">
							<label class="control-label" for="input01">選擇文件:</label>
							<div style="display:inline-block;margin-left:20px" id="chooseFile"><a style="width:90px;display:inline-block;background:#eaeaea;border:1px solid #ddd;text-align:center;padding:2px"  href="javascript:void(0);" id="chooseFileBtn">上傳</a></div>
							<span id="file_name"></span>
						</div> 
							<div class="control-group">
								<label class="control-label" for="input01">標題:</label>
								<div class="controls">
									<input type="text" class="input-xlarge" id="input01" name="title" onkeyup="checkTitle()" onkeydown="checkTitle()">
									<span id="title_error_span" style="display:none">
										<img src="static/images/shipin/error02.gif" width="17" height="17" alt="" />
										&nbsp;<span id="title_error_text">請輸入標題</span>
									</span>
									<span id="title_right_span" style="display:none">
										<img src="static/images/shipin/right.gif" width="17" height="17" alt=""/>
										&nbsp;<span>標題可用</span>
									</span>
									
								</div>
							</div>
							<div class="control-group">
								<label class="control-label" for="textarea">簡介:</label>
								<div class="controls">
									<textarea class="input-xlarge" id="textarea" rows="3" name="description" onkeyup="checkDric()" onkeydown="checkDric()"></textarea>
									<span id="description_error_span" style="display:none">
										<img src="static/images/shipin/error02.gif" width="17" height="17" alt="" />
										&nbsp;<span id="description_error_text">簡介過長</span>
									</span>
									<span id="description_right_span" style="display:none">
										<img src="static/images/shipin/right.gif" width="17" height="17" alt=""/>
										&nbsp;<span>簡介可用</span>
									</span>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label" for="input02">標簽:</label>
								<div class="controls">
									<input type="text" class="input-xlarge" id="input02" name="tags" onkeyup="checkTags()" onkeydown="checkTags()">
										<span class="help-inline"></span>
									<span id="tags_error_span" style="display:none">
										<img src="static/images/shipin/error02.gif" width="17" height="17" alt="" />
										&nbsp;<span id="tags_error_text">請輸入標簽</span>
									</span>
									<span id="tags_right_span" style="display:none">
										<img src="static/images/shipin/right.gif" width="17" height="17" alt=""/>
										&nbsp;<span>標簽可用</span>
									</span>
								</div>
							</div>
							<div class="form-actions">
								<button type="button" disabled="disabled" class="btn btn-primary start"  id="btn-upload-start" >
									<i class="icon-upload icon-white"></i>
									<span>開始上傳</span>
								</button>
								<div class="percent" id="percent"></div>
    							<div class="percent_text" id="percent_text"></div>
							</div>
							</fieldset>
						</form>
						<div class="row" >
							<div class="span5" id="upload-status-wraper" ></div>
						</div>
						<div class="well"><h3>說明</h3><ul><li>最大支持上傳<strong>1 GB</strong> 視頻文件</li><li>
							允許上傳的視頻格式為:wmv,avi,dat,asf,rm,rmvb,ram,mpg,mpeg,3gp,mov,mp4,m4v,dvix,dv,dat,
							<br/>
							mkv,flv,vob,ram,qt,divx,cpk,fli,flc,mod。不符合格式的視頻將會被丟棄,請確保視頻格式的正確性,避免上傳失敗
						</li></ul>
						</div>
					</div>

JS代碼

/*解決input中placeholder值在ie中無法支持的問題*/
		    $(document).ready(function(){
		        var doc=document,inputs=doc.getElementsByTagName('input'),supportPlaceholder='placeholder'in doc.createElement('input'),placeholder=function(input){var text=input.getAttribute('placeholder'),defaultValue=input.defaultValue;
		        if(defaultValue==''){ input.value=text}
		          input.onfocus=function(){
		              if(input.value===text){this.value=''}};
		              input.onblur=function(){if(input.value===''){this.value=text}}};
		              if(!supportPlaceholder){
		                  for(var i=0,len=inputs.length;i<len;i++){var input=inputs[i],text=input.getAttribute('placeholder');
		                  if(input.type==='text'&&text){placeholder(input)}
		            }
		        }
		   // 文件上傳按鈕div,這個div包裹文件上傳按鈕。文件上傳按鈕貌似不能是button類型,不知道為什麽,反正用的是他們demo裏的沒有變
	            var btn = document.getElementById("chooseFile");
	            // 初始化
                var vcop = new Q.vcopClient({
                  uploadBtn:{
                      dom:btn,
                      btnH:"32px",
                      btnW:"62px",
                      btnT:"100px",
                      btnL:"100px",
                      btnZ:"999",
                      hasBind:false},
                  appKey:"XXXXXXXXXXX",  // 填寫申請的app key 
                  appSecret:"XXXXXXXXXXXXXXXXXXXXXXX", // 填寫app secret
                  managerUrl:"http://openapi.iqiyi.com/",
                  uploadUrl:"http://upload.iqiyi.com/",
          		  needMeta:false
              	});
              	// 企業幾授權
                vcop.getAuthEnterprise(function (data) {
                    if(data){
                        vcop.authtoken = data.data.access_token;
                    }
                });
                // 文件信息
                var fileinfo = null;
                // 上傳組件
                var uoploader = null;
                // 上傳點擊事件
              	$("#chooseFileBtn").click(function(){
              		uoploader=vcop.initUpload({
    				slicesize:1024*128,
        	                access_token:vcop.authtoken, 
        	                device_id:"test", 
        	                uid:"test",
        	                allowType:["xv","avi","dat","mpg","mpeg","vob","mkv","mov","wmv","asf","rm","rmvb","ram","flv","mp4","3gp","dv","qt","divx","cpk","fli","flc","m4v","pfv"]  // 重置類型
        	                }, {
    	                onSuccess:function (data) {
    	                    if(data && data.data){
    	                        fileinfo = data.data;
    	                        $("#file_name").text(data.data.file_name);
    	                        $("#input01").val(data.data.file_name);
    	                        $("#textarea").val(data.data.file_name);
    	                        checkDric();
	    	   					checkTitle();
	    	   					checkTags();
    	                    }
    	                },
    	                onError:function (data) {
    	                    alert("錯誤");
    	                }}
    	            );
    	                // 初始化上傳組件
              		uoploader.initOneFile({btnW:"100px",btnH:"100px",btnT:"100px",btnL:"12px"});
                });
		        
                // 開始上傳
              	$("#btn-upload-start").click(function(){
                  	// 上傳按鈕不可用
					$("#btn-upload-start").attr("disabled","disabled");
					// 設置meta信息
					vcop.setMetadata({
			            file_id:fileinfo.file_id,
			            file_name:fileinfo.file_name,
			            description:fileinfo.file_name, 
			            uploader:uoploader          // 20130819 需手工設置meta
			        }, function (data) {
				        console.log(data);
			        })
			        // 開始上傳
              		uoploader.startUpload(fileinfo, {
                        onFinish:function (data) {
              				$("#btn-upload-start").attr("disabled",false);
                            if (data && data.manualFinish === true) {
                                uoploader.finishUpload({
                                    onSuccess:function () {
                                        window.location.href='<%=basePath%>personal/uploadVideo?videoId='+fileinfo.file_id ;
                                    },
                                    onError:function () {
                                        alert("上傳失敗");
                                    }
                                });
                            }else{
                                alert("上傳成功");
                            }
                            setTimeout(function () {
                                uoploader.delLocal(fileinfo.file_name,fileinfo.file_id);     // 20141227
                                resetPer();
                            }, 2000);
                        },
                        onError:function (data) {
                        	$("#btn-upload-start").attr("disabled",false);
                            if(data.msg){
                                // 續傳
                                if(data.msg=='network break down'){
                                    breakdown=true;
                                    uoploader.pauseUpload();
                                }
                            }
                            else{
                               alert("上傳失敗");
                            }
                            
                        },
                        onProgress:function (data) {    // 5/7 增加速度,剩余時間
                        	var per = document.getElementById("percent");
                            per.style.width = data.percent + "%";
                            $("#percent_text").text("上傳中....速度:"+data.speed+"kb/s , 剩余時間:"+data.remainTime + "s");
                        }
                    });
                });
		    });
                
  
  function checkTitle(){
  	//顯示數據
  	$("#title_error_span").hide();
	$("#title_right_span").hide();
	//獲取昵稱
	var title = $("#input01").val();
	//判斷用戶名是否為空
	if(title == "" || title == null){
		$("#title_right_span").hide();
		$("#title_error_span").show();
		$("#btn-upload-start").attr("disabled","disabled");
	}else if(title.length>30){
		$("#title_error_text").text("標題最多能輸入30個字");
		$("#title_right_span").hide();
		$("#title_error_span").show();
		$("#btn-upload-start").attr("disabled","disabled");
	}else{
		$("#title_error_span").hide();
		$("#title_right_span").show();
		$("#btn-upload-start").attr("disabled",false);
	}
  }
  	
  	
  function checkTags(){
	  var txt=new RegExp("[ ,\\`,\\~,\\!,\\@,\#,\\$,\\%,\\^,\\+,\\*,\\&,\\\\,\\/,\\?,\\|,\\:,\\.,\\<,\\>,\\{,\\},\\(,\\),\\',\\;,\\=,\"]");
  //顯示數據
	$("#tags_error_span").hide();
  	$("#tags_right_span").hide();
	var tags = $("#input02").val();
	//判斷用戶名是否為空
	if(tags == "" || tags == null){
		 $("#tags_right_span").hide();
		 $("#tags_error_span").show();
		 $("#btn-upload-start").attr("disabled","disabled");
	}else if(tags.length<2 || tags.length>12){
		 $("#tags_right_span").hide();
		 $("#tags_error_span").show();
		 $("#tags_error_text").text("標簽內容限定2~12的字符");
		 $("#btn-upload-start").attr("disabled","disabled");
	}   //特殊字符正則表達式
	else  if (txt.test(tags)){
		 $("#tags_right_span").hide();
		 $("#tags_error_span").show();
		 $("#tags_error_text").text("標簽含有特殊字符");
		 $("#btn-upload-start").attr("disabled","disabled");
    }else{
		 $("#tags_error_span").hide();
		 $("#tags_right_span").show();
		 $("#btn-upload-start").attr("disabled",false);
	}
  }
  /**
   * 檢查簡介
   */
  function checkDric(){
	//顯示數據
	$("#description_error_span").hide();
	$("#description_right_span").hide();
	  var content = $("#textarea").val().toString();
	  
	  var len = 0;
		if (content != null && content != "") {
			for ( var j = 0; j < content.length; j++) {
				var str = content.charAt(j);
				var reg = /^[\u4E00-\u9FA5]+$/;
				if (reg.test(str)) {
					len += 2;
				} else {
					len += 1;
				}
			}
		}
		
	  if(content == "" || len == 0 ){
		  $("#description_right_span").hide();
		  $("#description_error_text").text("請輸入簡介");
		  $("#description_error_span").show();
		  $("#btn-upload-start").attr("disabled","disabled");
	  }
	 
	  if(len <= 25 && len >0){
		  $("#description_error_span").hide();
		  $("#description_right_span").show();
		  $("#btn-upload-start").attr("disabled",false);
	  }else{
		  $("#description_right_span").hide();
		  $("#description_error_span").show();
		  $("#btn-upload-start").attr("disabled","disabled");
	  }
	  
  }

上傳完成後,頁面播放。JS代碼

// 獲取視頻id
	var videoId = $("#videoId").attr("value");
	// 初始化
	var vcop = new Q.vcopClient({
        appKey:"618c7aca5e6d47648e6c4d6fd2e246af",  // 填寫申請的app key 
        appSecret:"13a3fbb37e707ec19322c0478d860e7c", // 填寫app secret
        managerUrl:"http://openapi.iqiyi.com/",
        uploadUrl:"http://upload.iqiyi.com/",
		needMeta:false
    	});
	  // 授權
    vcop.getAuthEnterprise(function (data) {
          if(data){
              vcop.authtoken = data.data.access_token;
              console.log(vcop.authtoken);
              // 獲取視頻信息
              vcop.getVideoInfo({
                  file_ids:videoId // 獲取視頻信息
              }, function (result) {
            	  console.log(result);
            	  console.log("1:"+result);
            	  console.log("2:"+(result.code == "A00000"));
            	  if(result.code == "A00000"){
            		  var _r = result.data;
            		  console.log("3:"+_r)
            		  console.log("4:"+(_r != '[]'));
            		  if(_r != '[]' && _r != undefined && _r != '' && _r != null){
            			  if(_r[0].fileStatus == 1){ // 發布中
            				imghtml = "<img  src='static/images/shipin/shipin_zhuanma.gif' />";
                      		$("#shipin_img_div").html(imghtml);
            			  }else if(_r[0].fileStatus == 2){ // 已經發布
            				$("#shiping_img_div").css("display","none");
            			        // 這行代碼主要是為了獲取vid和tvid
            				$.get("http://openapi.iqiyi.com/api/file/fullStatus?access_token="+vcop.authtoken+"&file_id="+videoId,function(data){
            					data = $.parseJSON(data);
            					var swfUrl = data.data.swfurl;
            					var vid =  swfUrl.substring(swfUrl.indexOf("vid=") + 4, swfUrl.indexOf("&tvId"));
            					var tvid = swfUrl.substring(swfUrl.indexOf("tvId=") + 5, swfUrl.indexOf("&cnId"));
            					// 這行代碼,copy open.iqiyi.com -->我的應用 -->播放器設置的那段代碼
            					imghtml = "<iframe src='http://open.iqiyi.com/developer/player_js/coopPlayerIndex.html?vid="+vid+"&tvId="+tvid+"&sign=5dd681d8af3e02e699f7648b09d6a7cacd269ed2e98f3fa0b3c125d1df1283b3&appKey=618c7aca5e6d47648e6c4d6fd2e246af&appId=8769' frameborder='0' width='100%' height='100%' allowfullscreen='true'></iframe>";
            					$("#youkuplayer").html(imghtml).css("display",'inline-block');
            				});
            			  }else{ //審核未通過,不存在或已刪除 ,上傳中
            				imghtml = "<img  src='static/images/shipin/shipin_pingbi.gif' />";
                      		$("#shipin_img_div").html(imghtml);
            			  }
            		  }else{
            			imghtml = "<img  src='static/images/shipin/shipin_zhuanma.gif' />";
                    	$("#shipin_img_div").html(imghtml);
            		  }
            	  }
              });
          }
      });



使用愛奇藝開放平臺上傳視頻