暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

video.js 30KB

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. editor.execCommand('insertvideo', {
  115. url: convert_url(url),
  116. width: width.value,
  117. height: height.value,
  118. align: align
  119. }, isModifyUploadVideo ? 'upload':null);
  120. }
  121. /**
  122. * 将元素id下的所有代表视频的图片插入编辑器中
  123. * @param id
  124. */
  125. function insertSearch(id){
  126. var imgs = domUtils.getElementsByTagName($G(id),"img"),
  127. videoObjs=[];
  128. for(var i=0,img; img=imgs[i++];){
  129. if(img.getAttribute("selected")){
  130. videoObjs.push({
  131. url:img.getAttribute("ue_video_url"),
  132. width:420,
  133. height:280,
  134. align:"none"
  135. });
  136. }
  137. }
  138. editor.execCommand('insertvideo',videoObjs);
  139. }
  140. /**
  141. * 找到id下具有focus类的节点并返回该节点下的某个属性
  142. * @param id
  143. * @param returnProperty
  144. */
  145. function findFocus( id, returnProperty ) {
  146. var tabs = $G( id ).children,
  147. property;
  148. for ( var i = 0, ci; ci = tabs[i++]; ) {
  149. if ( ci.className=="focus" ) {
  150. property = ci.getAttribute( returnProperty );
  151. break;
  152. }
  153. }
  154. return property;
  155. }
  156. function convert_url(url){
  157. if ( !url ) return '';
  158. url = utils.trim(url)
  159. .replace(/v\.youku\.com\/v_show\/id_([\w\-=]+)\.html/i, 'player.youku.com/player.php/sid/$1/v.swf')
  160. .replace(/(www\.)?youtube\.com\/watch\?v=([\w\-]+)/i, "www.youtube.com/v/$2")
  161. .replace(/youtu.be\/(\w+)$/i, "www.youtube.com/v/$1")
  162. .replace(/v\.ku6\.com\/.+\/([\w\.]+)\.html.*$/i, "player.ku6.com/refer/$1/v.swf")
  163. .replace(/www\.56\.com\/u\d+\/v_([\w\-]+)\.html/i, "player.56.com/v_$1.swf")
  164. .replace(/www.56.com\/w\d+\/play_album\-aid\-\d+_vid\-([^.]+)\.html/i, "player.56.com/v_$1.swf")
  165. .replace(/v\.pps\.tv\/play_([\w]+)\.html.*$/i, "player.pps.tv/player/sid/$1/v.swf")
  166. .replace(/www\.letv\.com\/ptv\/vplay\/([\d]+)\.html.*$/i, "i7.imgs.letv.com/player/swfPlayer.swf?id=$1&autoplay=0")
  167. .replace(/www\.tudou\.com\/programs\/view\/([\w\-]+)\/?/i, "www.tudou.com/v/$1")
  168. .replace(/v\.qq\.com\/cover\/[\w]+\/[\w]+\/([\w]+)\.html/i, "static.video.qq.com/TPout.swf?vid=$1")
  169. .replace(/v\.qq\.com\/.+[\?\&]vid=([^&]+).*$/i, "static.video.qq.com/TPout.swf?vid=$1")
  170. .replace(/my\.tv\.sohu\.com\/[\w]+\/[\d]+\/([\d]+)\.shtml.*$/i, "share.vrs.sohu.com/my/v.swf&id=$1");
  171. return url;
  172. }
  173. /**
  174. * 检测传入的所有input框中输入的长宽是否是正数
  175. * @param nodes input框集合,
  176. */
  177. function checkNum( nodes ) {
  178. for ( var i = 0, ci; ci = nodes[i++]; ) {
  179. var value = ci.value;
  180. if ( !isNumber( value ) && value) {
  181. alert( lang.numError );
  182. ci.value = "";
  183. ci.focus();
  184. return false;
  185. }
  186. }
  187. return true;
  188. }
  189. /**
  190. * 数字判断
  191. * @param value
  192. */
  193. function isNumber( value ) {
  194. return /(0|^[1-9]\d*$)/.test( value );
  195. }
  196. /**
  197. * 创建图片浮动选择按钮
  198. * @param ids
  199. */
  200. function createAlignButton( ids ) {
  201. for ( var i = 0, ci; ci = ids[i++]; ) {
  202. var floatContainer = $G( ci ),
  203. nameMaps = {"none":lang['default'], "left":lang.floatLeft, "right":lang.floatRight, "center":lang.block};
  204. for ( var j in nameMaps ) {
  205. var div = document.createElement( "div" );
  206. div.setAttribute( "name", j );
  207. if ( j == "none" ) div.className="focus";
  208. div.style.cssText = "background:url(images/" + j + "_focus.jpg);";
  209. div.setAttribute( "title", nameMaps[j] );
  210. floatContainer.appendChild( div );
  211. }
  212. switchSelect( ci );
  213. }
  214. }
  215. /**
  216. * 选择切换
  217. * @param selectParentId
  218. */
  219. function switchSelect( selectParentId ) {
  220. var selects = $G( selectParentId ).children;
  221. for ( var i = 0, ci; ci = selects[i++]; ) {
  222. domUtils.on( ci, "click", function () {
  223. for ( var j = 0, cj; cj = selects[j++]; ) {
  224. cj.className = "";
  225. cj.removeAttribute && cj.removeAttribute( "class" );
  226. }
  227. this.className = "focus";
  228. } )
  229. }
  230. }
  231. /**
  232. * 监听url改变事件
  233. * @param url
  234. */
  235. function addUrlChangeListener(url){
  236. if (browser.ie) {
  237. url.onpropertychange = function () {
  238. createPreviewVideo( this.value );
  239. }
  240. } else {
  241. url.addEventListener( "input", function () {
  242. createPreviewVideo( this.value );
  243. }, false );
  244. }
  245. }
  246. /**
  247. * 根据url生成视频预览
  248. * @param url
  249. */
  250. function createPreviewVideo(url){
  251. if ( !url )return;
  252. var conUrl = convert_url(url);
  253. conUrl = utils.unhtmlForUrl(conUrl);
  254. // 对flash和其他格式处理 by 小虎哥
  255. if(conUrl.indexOf(".swf") >= 0 ) {
  256. $G("preview").innerHTML = '<div class="previewMsg"><span>'+lang.urlError+'</span></div>'+
  257. '<embed class="previewVideo" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  258. ' src="' + conUrl + '"' +
  259. ' width="' + 420 + '"' +
  260. ' height="' + 280 + '"' +
  261. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >' +
  262. '</embed>';
  263. } else {
  264. $G("preview").innerHTML = '<div class="previewMsg"><span>'+lang.urlError+'</span></div>'+
  265. '<video controls="controls" autoplay="autoplay" '+
  266. ' width="' + 420 + '"' +
  267. ' height="' + 280 + '"' +
  268. ' style="max-width:100%;">' +
  269. ' <source src="' + conUrl + '"' + ' type="video/mp4" />' +
  270. '</video>';
  271. }
  272. }
  273. /* 插入上传视频 */
  274. function insertUpload(){
  275. var videoObjs=[],
  276. uploadDir = editor.getOpt('videoUrlPrefix'),
  277. width = parseInt($G('upload_width').value, 10) || 420,
  278. height = parseInt($G('upload_height').value, 10) || 280,
  279. align = findFocus("upload_alignment","name") || 'none';
  280. for(var key in uploadVideoList) {
  281. var file = uploadVideoList[key];
  282. videoObjs.push({
  283. url: uploadDir + file.url,
  284. width:width,
  285. height:height,
  286. align:align
  287. });
  288. }
  289. var count = uploadFile.getQueueCount();
  290. if (count) {
  291. $('.info', '#queueList').html('<span style="color:red;">' + '还有2个未上传文件'.replace(/[\d]/, count) + '</span>');
  292. return false;
  293. } else {
  294. editor.execCommand('insertvideo', videoObjs, 'upload');
  295. }
  296. }
  297. /*初始化上传标签*/
  298. function initUpload(){
  299. uploadFile = new UploadFile('queueList');
  300. }
  301. /* 上传附件 */
  302. function UploadFile(target) {
  303. this.$wrap = target.constructor == String ? $('#' + target) : $(target);
  304. this.init();
  305. }
  306. UploadFile.prototype = {
  307. init: function () {
  308. this.fileList = [];
  309. this.initContainer();
  310. this.initUploader();
  311. },
  312. initContainer: function () {
  313. this.$queue = this.$wrap.find('.filelist');
  314. },
  315. /* 初始化容器 */
  316. initUploader: function () {
  317. var _this = this,
  318. $ = jQuery, // just in case. Make sure it's not an other libaray.
  319. $wrap = _this.$wrap,
  320. // 图片容器
  321. $queue = $wrap.find('.filelist'),
  322. // 状态栏,包括进度和控制按钮
  323. $statusBar = $wrap.find('.statusBar'),
  324. // 文件总体选择信息。
  325. $info = $statusBar.find('.info'),
  326. // 上传按钮
  327. $upload = $wrap.find('.uploadBtn'),
  328. // 上传按钮
  329. $filePickerBtn = $wrap.find('.filePickerBtn'),
  330. // 上传按钮
  331. $filePickerBlock = $wrap.find('.filePickerBlock'),
  332. // 没选择文件之前的内容。
  333. $placeHolder = $wrap.find('.placeholder'),
  334. // 总体进度条
  335. $progress = $statusBar.find('.progress').hide(),
  336. // 添加的文件数量
  337. fileCount = 0,
  338. // 添加的文件总大小
  339. fileSize = 0,
  340. // 优化retina, 在retina下这个值是2
  341. ratio = window.devicePixelRatio || 1,
  342. // 缩略图大小
  343. thumbnailWidth = 113 * ratio,
  344. thumbnailHeight = 113 * ratio,
  345. // 可能有pedding, ready, uploading, confirm, done.
  346. state = '',
  347. // 所有文件的进度信息,key为file id
  348. percentages = {},
  349. supportTransition = (function () {
  350. var s = document.createElement('p').style,
  351. r = 'transition' in s ||
  352. 'WebkitTransition' in s ||
  353. 'MozTransition' in s ||
  354. 'msTransition' in s ||
  355. 'OTransition' in s;
  356. s = null;
  357. return r;
  358. })(),
  359. // WebUploader实例
  360. uploader,
  361. actionUrl = editor.getActionUrl(editor.getOpt('videoActionName')),
  362. fileMaxSize = editor.getOpt('videoMaxSize'),
  363. acceptExtensions = (editor.getOpt('videoAllowFiles') || []).join('').replace(/\./g, ',').replace(/^[,]/, '');;
  364. if (!WebUploader.Uploader.support()) {
  365. $('#filePickerReady').after($('<div>').html(lang.errorNotSupport)).hide();
  366. return;
  367. } else if (!editor.getOpt('videoActionName')) {
  368. $('#filePickerReady').after($('<div>').html(lang.errorLoadConfig)).hide();
  369. return;
  370. }
  371. uploader = _this.uploader = WebUploader.create({
  372. pick: {
  373. id: '#filePickerReady',
  374. label: lang.uploadSelectFile
  375. },
  376. swf: '../../third-party/webuploader/Uploader.swf',
  377. server: actionUrl,
  378. fileVal: editor.getOpt('videoFieldName'),
  379. duplicate: true,
  380. fileSingleSizeLimit: fileMaxSize,
  381. compress: false
  382. });
  383. uploader.addButton({
  384. id: '#filePickerBlock'
  385. });
  386. uploader.addButton({
  387. id: '#filePickerBtn',
  388. label: lang.uploadAddFile
  389. });
  390. setState('pedding');
  391. // 当有文件添加进来时执行,负责view的创建
  392. function addFile(file) {
  393. var $li = $('<li id="' + file.id + '">' +
  394. '<p class="title">' + file.name + '</p>' +
  395. '<p class="imgWrap"></p>' +
  396. '<p class="progress"><span></span></p>' +
  397. '</li>'),
  398. $btns = $('<div class="file-panel">' +
  399. '<span class="cancel">' + lang.uploadDelete + '</span>' +
  400. '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
  401. '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
  402. $prgress = $li.find('p.progress span'),
  403. $wrap = $li.find('p.imgWrap'),
  404. $info = $('<p class="error"></p>').hide().appendTo($li),
  405. showError = function (code) {
  406. switch (code) {
  407. case 'exceed_size':
  408. text = lang.errorExceedSize;
  409. break;
  410. case 'interrupt':
  411. text = lang.errorInterrupt;
  412. break;
  413. case 'http':
  414. text = lang.errorHttp;
  415. break;
  416. case 'not_allow_type':
  417. text = lang.errorFileType;
  418. break;
  419. default:
  420. text = lang.errorUploadRetry;
  421. break;
  422. }
  423. setTimeout(function(){
  424. $info.text(text).show();
  425. },1);
  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. })();