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.

855 lines
32 KiB

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