video.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. /**
  2. * Created by JetBrains PhpStorm.
  3. * User: taoqili
  4. * Date: 12-2-20
  5. * Time: 上午11:19
  6. * To change this template use File | Settings | File Templates.
  7. */
  8. (function(){
  9. var video = {},
  10. uploadVideoList = [],
  11. isModifyUploadVideo = false,
  12. uploadFile;
  13. window.onload = function(){
  14. $focus($G("videoUrl"));
  15. initTabs();
  16. initVideo();
  17. initUpload();
  18. };
  19. /* 初始化tab标签 */
  20. function initTabs(){
  21. var tabs = $G('tabHeads').children;
  22. for (var i = 0; i < tabs.length; i++) {
  23. domUtils.on(tabs[i], "click", function (e) {
  24. var j, bodyId, target = e.target || e.srcElement;
  25. for (j = 0; j < tabs.length; j++) {
  26. bodyId = tabs[j].getAttribute('data-content-id');
  27. if(tabs[j] == target){
  28. domUtils.addClass(tabs[j], 'focus');
  29. domUtils.addClass($G(bodyId), 'focus');
  30. }else {
  31. domUtils.removeClasses(tabs[j], 'focus');
  32. domUtils.removeClasses($G(bodyId), 'focus');
  33. }
  34. }
  35. });
  36. }
  37. }
  38. function initVideo(){
  39. createAlignButton( ["videoFloat", "upload_alignment"] );
  40. addUrlChangeListener($G("videoUrl"));
  41. addOkListener();
  42. //编辑视频时初始化相关信息
  43. (function(){
  44. var img = editor.selection.getRange().getClosedNode(),url;
  45. if(img && img.className){
  46. var hasFakedClass = (img.className == "edui-faked-video"),
  47. hasUploadClass = img.className.indexOf("edui-upload-video")!=-1;
  48. if(hasFakedClass || hasUploadClass) {
  49. $G("videoUrl").value = url = img.getAttribute("_url");
  50. $G("videoWidth").value = img.width;
  51. $G("videoHeight").value = img.height;
  52. var align = domUtils.getComputedStyle(img,"float"),
  53. parentAlign = domUtils.getComputedStyle(img.parentNode,"text-align");
  54. updateAlignButton(parentAlign==="center"?"center":align);
  55. }
  56. if(hasUploadClass) {
  57. isModifyUploadVideo = true;
  58. }
  59. }
  60. createPreviewVideo(url);
  61. })();
  62. }
  63. /**
  64. * 监听确认和取消两个按钮事件,用户执行插入或者清空正在播放的视频实例操作
  65. */
  66. function addOkListener(){
  67. dialog.onok = function(){
  68. $G("preview").innerHTML = "";
  69. var currentTab = findFocus("tabHeads","tabSrc");
  70. switch(currentTab){
  71. case "video":
  72. return insertSingle();
  73. break;
  74. case "videoSearch":
  75. return insertSearch("searchList");
  76. break;
  77. case "upload":
  78. return insertUpload();
  79. break;
  80. }
  81. };
  82. dialog.oncancel = function(){
  83. $G("preview").innerHTML = "";
  84. };
  85. }
  86. /**
  87. * 依据传入的align值更新按钮信息
  88. * @param align
  89. */
  90. function updateAlignButton( align ) {
  91. var aligns = $G( "videoFloat" ).children;
  92. for ( var i = 0, ci; ci = aligns[i++]; ) {
  93. if ( ci.getAttribute( "name" ) == align ) {
  94. if ( ci.className !="focus" ) {
  95. ci.className = "focus";
  96. }
  97. } else {
  98. if ( ci.className =="focus" ) {
  99. ci.className = "";
  100. }
  101. }
  102. }
  103. }
  104. /**
  105. * 将单个视频信息插入编辑器中
  106. */
  107. function insertSingle(){
  108. var width = $G("videoWidth"),
  109. height = $G("videoHeight"),
  110. url=$G('videoUrl').value,
  111. align = findFocus("videoFloat","name");
  112. if(!url) return false;
  113. if ( !checkNum( [width, height] ) ) return false;
  114. var newIframe = editor.document.createElement("iframe");
  115. var div;
  116. if(!width.value) width.value = '100%';
  117. if(!height.value) height.value = '250px';
  118. newIframe.setAttribute("src", convert_url(url));
  119. newIframe.setAttribute("width", width.value);
  120. newIframe.setAttribute("height", height.value);
  121. //newIframe.setAttribute("scrolling","no");
  122. newIframe.setAttribute("frameborder", "0", 0);
  123. newIframe.setAttribute("allowfullscreen", "allowfullscreen");
  124. newIframe.setAttribute("align", align);
  125. div = editor.document.createElement("div");
  126. div.appendChild(newIframe);
  127. editor.execCommand("inserthtml",div.innerHTML);
  128. /*editor.execCommand('insertvideo', {
  129. url: convert_url(url),
  130. width: width.value,
  131. height: height.value,
  132. align: align
  133. }, isModifyUploadVideo ? 'upload':null);*/
  134. }
  135. /**
  136. * 将元素id下的所有代表视频的图片插入编辑器中
  137. * @param id
  138. */
  139. function insertSearch(id){
  140. var imgs = domUtils.getElementsByTagName($G(id),"img"),
  141. videoObjs=[];
  142. for(var i=0,img; img=imgs[i++];){
  143. if(img.getAttribute("selected")){
  144. videoObjs.push({
  145. url:img.getAttribute("ue_video_url"),
  146. width:420,
  147. height:280,
  148. align:"none"
  149. });
  150. }
  151. }
  152. editor.execCommand('insertvideo',videoObjs);
  153. }
  154. /**
  155. * 找到id下具有focus类的节点并返回该节点下的某个属性
  156. * @param id
  157. * @param returnProperty
  158. */
  159. function findFocus( id, returnProperty ) {
  160. var tabs = $G( id ).children,
  161. property;
  162. for ( var i = 0, ci; ci = tabs[i++]; ) {
  163. if ( ci.className=="focus" ) {
  164. property = ci.getAttribute( returnProperty );
  165. break;
  166. }
  167. }
  168. return property;
  169. }
  170. function convert_url(url){
  171. if ( !url ) return '';
  172. url = utils.trim(url)
  173. .replace(/v\.youku\.com\/v_show\/id_([\w\-=]+)\.html/i, 'player.youku.com/embed/$1')
  174. .replace(/(www\.)?youtube\.com\/watch\?v=([\w\-]+)/i, "www.youtube.com/embed/$2")
  175. .replace(/youtu.be\/(\w+)$/i, "www.youtube.com/embed/$1")
  176. .replace(/v\.ku6\.com\/.+\/([\w\.]+)\.html.*$/i, "m.ku6.com/show/$1.html")
  177. .replace(/www\.56\.com\/u\d+\/v_([\w\-]+)\.html/i, "www.56.com/iframe/$1")
  178. .replace(/www.56.com\/w\d+\/play_album\-aid\-\d+_vid\-([^.]+)\.html/i, "www.56.com/iframe/$1")
  179. .replace(/tudou\.com\/(listplay|albumplay)\/([\w\-=]+)\/([\w\-=]+)\.html/i, "tudou.com/programs/view/html5embed.action?type=0&code=$3&lcode=$2")
  180. .replace(/tudou\.com\/programs\/view\/([\w\-=]+)\//i, "tudou.com/programs/view/html5embed.action?type=0&code=$1&lcode=")
  181. .replace(/v\.qq\.com\/page\/[\w]+\/[\w]+\/[\w]+\/([\w]+)\.html/i, "v.qq.com/iframe/player.html?vid=$1&tiny=0&auto=0")
  182. .replace(/v\.qq\.com\/cover\/[\w]+\/[\w]+\/([\w]+)\.html/i, "v.qq.com/iframe/player.html?vid=$1&tiny=0&auto=0")
  183. .replace(/v\.qq\.com\/.+[\?\&]vid=([^&]+).*$/i, "v.qq.com/iframe/player.html?vid=$1&tiny=0&auto=0")
  184. .replace(/my\.tv\.sohu\.com\/[\w]+\/([\d]+)\/([\d]+)\.shtml.*$/i, "tv.sohu.com/upload/static/share/share_play.html#$1_$2_0_9001_0");
  185. return url;
  186. }
  187. /**
  188. * 检测传入的所有input框中输入的长宽是否是正数
  189. * @param nodes input框集合,
  190. */
  191. function checkNum( nodes ) {
  192. for ( var i = 0, ci; ci = nodes[i++]; ) {
  193. var value = ci.value;
  194. if ( !isNumber( value ) && value) {
  195. alert( lang.numError );
  196. ci.value = "";
  197. ci.focus();
  198. return false;
  199. }
  200. }
  201. return true;
  202. }
  203. /**
  204. * 数字判断
  205. * @param value
  206. */
  207. function isNumber( value ) {
  208. return /(0|^[1-9]\d*$)/.test( value );
  209. }
  210. /**
  211. * 创建图片浮动选择按钮
  212. * @param ids
  213. */
  214. function createAlignButton( ids ) {
  215. for ( var i = 0, ci; ci = ids[i++]; ) {
  216. var floatContainer = $G( ci ),
  217. nameMaps = {"none":lang['default'], "left":lang.floatLeft, "right":lang.floatRight, "center":lang.block};
  218. for ( var j in nameMaps ) {
  219. var div = document.createElement( "div" );
  220. div.setAttribute( "name", j );
  221. if ( j == "none" ) div.className="focus";
  222. div.style.cssText = "background:url(images/" + j + "_focus.jpg);";
  223. div.setAttribute( "title", nameMaps[j] );
  224. floatContainer.appendChild( div );
  225. }
  226. switchSelect( ci );
  227. }
  228. }
  229. /**
  230. * 选择切换
  231. * @param selectParentId
  232. */
  233. function switchSelect( selectParentId ) {
  234. var selects = $G( selectParentId ).children;
  235. for ( var i = 0, ci; ci = selects[i++]; ) {
  236. domUtils.on( ci, "click", function () {
  237. for ( var j = 0, cj; cj = selects[j++]; ) {
  238. cj.className = "";
  239. cj.removeAttribute && cj.removeAttribute( "class" );
  240. }
  241. this.className = "focus";
  242. } )
  243. }
  244. }
  245. /**
  246. * 监听url改变事件
  247. * @param url
  248. */
  249. function addUrlChangeListener(url){
  250. if (browser.ie) {
  251. url.onpropertychange = function () {
  252. createPreviewVideo( this.value );
  253. }
  254. } else {
  255. url.addEventListener( "input", function () {
  256. createPreviewVideo( this.value );
  257. }, false );
  258. }
  259. }
  260. /**
  261. * 根据url生成视频预览
  262. * @param url
  263. */
  264. function createPreviewVideo(url){
  265. if ( !url )return;
  266. var conUrl = convert_url(url);
  267. $G("preview").innerHTML = '<div class="previewMsg"><span>'+lang.urlError+'</span></div>'+
  268. '<iframe class="previewVideo"' +
  269. ' src="' + conUrl + '"' +
  270. ' width="' + 420 + '"' +
  271. ' height="' + 280 + '"' +
  272. ' frameborder=0 allowfullscreen>' +
  273. '</iframe>';
  274. }
  275. /* 插入上传视频 */
  276. function insertUpload(){
  277. var videoObjs=[],
  278. uploadDir = editor.getOpt('videoUrlPrefix'),
  279. width = $G('upload_width').value || 420,
  280. height = $G('upload_height').value || 280,
  281. align = findFocus("upload_alignment","name") || 'none';
  282. for(var key in uploadVideoList) {
  283. var file = uploadVideoList[key];
  284. videoObjs.push({
  285. url: uploadDir + file.url,
  286. width:width,
  287. height:height,
  288. align:align
  289. });
  290. }
  291. var count = uploadFile.getQueueCount();
  292. if (count) {
  293. $('.info', '#queueList').html('<span style="color:red;">' + '还有2个未上传文件'.replace(/[\d]/, count) + '</span>');
  294. return false;
  295. } else {
  296. editor.execCommand('insertvideo', videoObjs, 'upload');
  297. }
  298. }
  299. /*初始化上传标签*/
  300. function initUpload(){
  301. uploadFile = new UploadFile('queueList');
  302. }
  303. /* 上传附件 */
  304. function UploadFile(target) {
  305. this.$wrap = target.constructor == String ? $('#' + target) : $(target);
  306. this.init();
  307. }
  308. UploadFile.prototype = {
  309. init: function () {
  310. this.fileList = [];
  311. this.initContainer();
  312. this.initUploader();
  313. },
  314. initContainer: function () {
  315. this.$queue = this.$wrap.find('.filelist');
  316. },
  317. /* 初始化容器 */
  318. initUploader: function () {
  319. var _this = this,
  320. $ = jQuery, // just in case. Make sure it's not an other libaray.
  321. $wrap = _this.$wrap,
  322. // 图片容器
  323. $queue = $wrap.find('.filelist'),
  324. // 状态栏,包括进度和控制按钮
  325. $statusBar = $wrap.find('.statusBar'),
  326. // 文件总体选择信息。
  327. $info = $statusBar.find('.info'),
  328. // 上传按钮
  329. $upload = $wrap.find('.uploadBtn'),
  330. // 上传按钮
  331. $filePickerBtn = $wrap.find('.filePickerBtn'),
  332. // 上传按钮
  333. $filePickerBlock = $wrap.find('.filePickerBlock'),
  334. // 没选择文件之前的内容。
  335. $placeHolder = $wrap.find('.placeholder'),
  336. // 总体进度条
  337. $progress = $statusBar.find('.progress').hide(),
  338. // 添加的文件数量
  339. fileCount = 0,
  340. // 添加的文件总大小
  341. fileSize = 0,
  342. // 优化retina, 在retina下这个值是2
  343. ratio = window.devicePixelRatio || 1,
  344. // 缩略图大小
  345. thumbnailWidth = 113 * ratio,
  346. thumbnailHeight = 113 * ratio,
  347. // 可能有pedding, ready, uploading, confirm, done.
  348. state = '',
  349. // 所有文件的进度信息,key为file id
  350. percentages = {},
  351. supportTransition = (function () {
  352. var s = document.createElement('p').style,
  353. r = 'transition' in s ||
  354. 'WebkitTransition' in s ||
  355. 'MozTransition' in s ||
  356. 'msTransition' in s ||
  357. 'OTransition' in s;
  358. s = null;
  359. return r;
  360. })(),
  361. // WebUploader实例
  362. uploader,
  363. actionUrl = editor.getActionUrl(editor.getOpt('videoActionName')),
  364. fileMaxSize = editor.getOpt('videoMaxSize'),
  365. acceptExtensions = (editor.getOpt('videoAllowFiles') || []).join('').replace(/\./g, ',').replace(/^[,]/, '');;
  366. if (!WebUploader.Uploader.support()) {
  367. $('#filePickerReady').after($('<div>').html(lang.errorNotSupport)).hide();
  368. return;
  369. } else if (!editor.getOpt('videoActionName')) {
  370. $('#filePickerReady').after($('<div>').html(lang.errorLoadConfig)).hide();
  371. return;
  372. }
  373. uploader = _this.uploader = WebUploader.create({
  374. pick: {
  375. id: '#filePickerReady',
  376. label: lang.uploadSelectFile
  377. },
  378. swf: '../../third-party/webuploader/Uploader.swf',
  379. server: actionUrl,
  380. fileVal: editor.getOpt('videoFieldName'),
  381. duplicate: true,
  382. fileSingleSizeLimit: fileMaxSize,
  383. compress: false
  384. });
  385. uploader.addButton({
  386. id: '#filePickerBlock'
  387. });
  388. uploader.addButton({
  389. id: '#filePickerBtn',
  390. label: lang.uploadAddFile
  391. });
  392. setState('pedding');
  393. // 当有文件添加进来时执行,负责view的创建
  394. function addFile(file) {
  395. var $li = $('<li id="' + file.id + '">' +
  396. '<p class="title">' + file.name + '</p>' +
  397. '<p class="imgWrap"></p>' +
  398. '<p class="progress"><span></span></p>' +
  399. '</li>'),
  400. $btns = $('<div class="file-panel">' +
  401. '<span class="cancel">' + lang.uploadDelete + '</span>' +
  402. '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
  403. '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
  404. $prgress = $li.find('p.progress span'),
  405. $wrap = $li.find('p.imgWrap'),
  406. $info = $('<p class="error"></p>').hide().appendTo($li),
  407. showError = function (code) {
  408. switch (code) {
  409. case 'exceed_size':
  410. text = lang.errorExceedSize;
  411. break;
  412. case 'interrupt':
  413. text = lang.errorInterrupt;
  414. break;
  415. case 'http':
  416. text = lang.errorHttp;
  417. break;
  418. case 'not_allow_type':
  419. text = lang.errorFileType;
  420. break;
  421. default:
  422. text = lang.errorUploadRetry;
  423. break;
  424. }
  425. $info.text(text).show();
  426. };
  427. if (file.getStatus() === 'invalid') {
  428. showError(file.statusText);
  429. } else {
  430. $wrap.text(lang.uploadPreview);
  431. if ('|png|jpg|jpeg|bmp|gif|'.indexOf('|'+file.ext.toLowerCase()+'|') == -1) {
  432. $wrap.empty().addClass('notimage').append('<i class="file-preview file-type-' + file.ext.toLowerCase() + '"></i>' +
  433. '<span class="file-title">' + file.name + '</span>');
  434. } else {
  435. if (browser.ie && browser.version <= 7) {
  436. $wrap.text(lang.uploadNoPreview);
  437. } else {
  438. uploader.makeThumb(file, function (error, src) {
  439. if (error || !src || (/^data:/.test(src) && browser.ie && browser.version <= 7)) {
  440. $wrap.text(lang.uploadNoPreview);
  441. } else {
  442. var $img = $('<img src="' + src + '">');
  443. $wrap.empty().append($img);
  444. $img.on('error', function () {
  445. $wrap.text(lang.uploadNoPreview);
  446. });
  447. }
  448. }, thumbnailWidth, thumbnailHeight);
  449. }
  450. }
  451. percentages[ file.id ] = [ file.size, 0 ];
  452. file.rotation = 0;
  453. /* 检查文件格式 */
  454. if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
  455. showError('not_allow_type');
  456. uploader.removeFile(file);
  457. }
  458. }
  459. file.on('statuschange', function (cur, prev) {
  460. if (prev === 'progress') {
  461. $prgress.hide().width(0);
  462. } else if (prev === 'queued') {
  463. $li.off('mouseenter mouseleave');
  464. $btns.remove();
  465. }
  466. // 成功
  467. if (cur === 'error' || cur === 'invalid') {
  468. showError(file.statusText);
  469. percentages[ file.id ][ 1 ] = 1;
  470. } else if (cur === 'interrupt') {
  471. showError('interrupt');
  472. } else if (cur === 'queued') {
  473. percentages[ file.id ][ 1 ] = 0;
  474. } else if (cur === 'progress') {
  475. $info.hide();
  476. $prgress.css('display', 'block');
  477. } else if (cur === 'complete') {
  478. }
  479. $li.removeClass('state-' + prev).addClass('state-' + cur);
  480. });
  481. $li.on('mouseenter', function () {
  482. $btns.stop().animate({height: 30});
  483. });
  484. $li.on('mouseleave', function () {
  485. $btns.stop().animate({height: 0});
  486. });
  487. $btns.on('click', 'span', function () {
  488. var index = $(this).index(),
  489. deg;
  490. switch (index) {
  491. case 0:
  492. uploader.removeFile(file);
  493. return;
  494. case 1:
  495. file.rotation += 90;
  496. break;
  497. case 2:
  498. file.rotation -= 90;
  499. break;
  500. }
  501. if (supportTransition) {
  502. deg = 'rotate(' + file.rotation + 'deg)';
  503. $wrap.css({
  504. '-webkit-transform': deg,
  505. '-mos-transform': deg,
  506. '-o-transform': deg,
  507. 'transform': deg
  508. });
  509. } else {
  510. $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
  511. }
  512. });
  513. $li.insertBefore($filePickerBlock);
  514. }
  515. // 负责view的销毁
  516. function removeFile(file) {
  517. var $li = $('#' + file.id);
  518. delete percentages[ file.id ];
  519. updateTotalProgress();
  520. $li.off().find('.file-panel').off().end().remove();
  521. }
  522. function updateTotalProgress() {
  523. var loaded = 0,
  524. total = 0,
  525. spans = $progress.children(),
  526. percent;
  527. $.each(percentages, function (k, v) {
  528. total += v[ 0 ];
  529. loaded += v[ 0 ] * v[ 1 ];
  530. });
  531. percent = total ? loaded / total : 0;
  532. spans.eq(0).text(Math.round(percent * 100) + '%');
  533. spans.eq(1).css('width', Math.round(percent * 100) + '%');
  534. updateStatus();
  535. }
  536. function setState(val, files) {
  537. if (val != state) {
  538. var stats = uploader.getStats();
  539. $upload.removeClass('state-' + state);
  540. $upload.addClass('state-' + val);
  541. switch (val) {
  542. /* 未选择文件 */
  543. case 'pedding':
  544. $queue.addClass('element-invisible');
  545. $statusBar.addClass('element-invisible');
  546. $placeHolder.removeClass('element-invisible');
  547. $progress.hide(); $info.hide();
  548. uploader.refresh();
  549. break;
  550. /* 可以开始上传 */
  551. case 'ready':
  552. $placeHolder.addClass('element-invisible');
  553. $queue.removeClass('element-invisible');
  554. $statusBar.removeClass('element-invisible');
  555. $progress.hide(); $info.show();
  556. $upload.text(lang.uploadStart);
  557. uploader.refresh();
  558. break;
  559. /* 上传中 */
  560. case 'uploading':
  561. $progress.show(); $info.hide();
  562. $upload.text(lang.uploadPause);
  563. break;
  564. /* 暂停上传 */
  565. case 'paused':
  566. $progress.show(); $info.hide();
  567. $upload.text(lang.uploadContinue);
  568. break;
  569. case 'confirm':
  570. $progress.show(); $info.hide();
  571. $upload.text(lang.uploadStart);
  572. stats = uploader.getStats();
  573. if (stats.successNum && !stats.uploadFailNum) {
  574. setState('finish');
  575. return;
  576. }
  577. break;
  578. case 'finish':
  579. $progress.hide(); $info.show();
  580. if (stats.uploadFailNum) {
  581. $upload.text(lang.uploadRetry);
  582. } else {
  583. $upload.text(lang.uploadStart);
  584. }
  585. break;
  586. }
  587. state = val;
  588. updateStatus();
  589. }
  590. if (!_this.getQueueCount()) {
  591. $upload.addClass('disabled')
  592. } else {
  593. $upload.removeClass('disabled')
  594. }
  595. }
  596. function updateStatus() {
  597. var text = '', stats;
  598. if (state === 'ready') {
  599. text = lang.updateStatusReady.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize));
  600. } else if (state === 'confirm') {
  601. stats = uploader.getStats();
  602. if (stats.uploadFailNum) {
  603. text = lang.updateStatusConfirm.replace('_', stats.successNum).replace('_', stats.successNum);
  604. }
  605. } else {
  606. stats = uploader.getStats();
  607. text = lang.updateStatusFinish.replace('_', fileCount).
  608. replace('_KB', WebUploader.formatSize(fileSize)).
  609. replace('_', stats.successNum);
  610. if (stats.uploadFailNum) {
  611. text += lang.updateStatusError.replace('_', stats.uploadFailNum);
  612. }
  613. }
  614. $info.html(text);
  615. }
  616. uploader.on('fileQueued', function (file) {
  617. fileCount++;
  618. fileSize += file.size;
  619. if (fileCount === 1) {
  620. $placeHolder.addClass('element-invisible');
  621. $statusBar.show();
  622. }
  623. addFile(file);
  624. });
  625. uploader.on('fileDequeued', function (file) {
  626. fileCount--;
  627. fileSize -= file.size;
  628. removeFile(file);
  629. updateTotalProgress();
  630. });
  631. uploader.on('filesQueued', function (file) {
  632. if (!uploader.isInProgress() && (state == 'pedding' || state == 'finish' || state == 'confirm' || state == 'ready')) {
  633. setState('ready');
  634. }
  635. updateTotalProgress();
  636. });
  637. uploader.on('all', function (type, files) {
  638. switch (type) {
  639. case 'uploadFinished':
  640. setState('confirm', files);
  641. break;
  642. case 'startUpload':
  643. /* 添加额外的GET参数 */
  644. var params = utils.serializeParam(editor.queryCommandValue('serverparam')) || '',
  645. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + 'encode=utf-8&' + params);
  646. uploader.option('server', url);
  647. setState('uploading', files);
  648. break;
  649. case 'stopUpload':
  650. setState('paused', files);
  651. break;
  652. }
  653. });
  654. uploader.on('uploadBeforeSend', function (file, data, header) {
  655. //这里可以通过data对象添加POST参数
  656. header['X_Requested_With'] = 'XMLHttpRequest';
  657. });
  658. uploader.on('uploadProgress', function (file, percentage) {
  659. var $li = $('#' + file.id),
  660. $percent = $li.find('.progress span');
  661. $percent.css('width', percentage * 100 + '%');
  662. percentages[ file.id ][ 1 ] = percentage;
  663. updateTotalProgress();
  664. });
  665. uploader.on('uploadSuccess', function (file, ret) {
  666. var $file = $('#' + file.id);
  667. try {
  668. var responseText = (ret._raw || ret),
  669. json = utils.str2json(responseText);
  670. if (json.state == 'SUCCESS') {
  671. uploadVideoList.push({
  672. 'url': json.url,
  673. 'type': json.type,
  674. 'original':json.original
  675. });
  676. $file.append('<span class="success"></span>');
  677. } else {
  678. $file.find('.error').text(json.state).show();
  679. }
  680. } catch (e) {
  681. $file.find('.error').text(lang.errorServerUpload).show();
  682. }
  683. });
  684. uploader.on('uploadError', function (file, code) {
  685. });
  686. uploader.on('error', function (code, file) {
  687. if (code == 'Q_TYPE_DENIED' || code == 'F_EXCEED_SIZE') {
  688. addFile(file);
  689. }
  690. });
  691. uploader.on('uploadComplete', function (file, ret) {
  692. });
  693. $upload.on('click', function () {
  694. if ($(this).hasClass('disabled')) {
  695. return false;
  696. }
  697. if (state === 'ready') {
  698. uploader.upload();
  699. } else if (state === 'paused') {
  700. uploader.upload();
  701. } else if (state === 'uploading') {
  702. uploader.stop();
  703. }
  704. });
  705. $upload.addClass('state-' + state);
  706. updateTotalProgress();
  707. },
  708. getQueueCount: function () {
  709. var file, i, status, readyFile = 0, files = this.uploader.getFiles();
  710. for (i = 0; file = files[i++]; ) {
  711. status = file.getStatus();
  712. if (status == 'queued' || status == 'uploading' || status == 'progress') readyFile++;
  713. }
  714. return readyFile;
  715. },
  716. refresh: function(){
  717. this.uploader.refresh();
  718. }
  719. };
  720. })();