Ei kuvausta
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.

upload.js 31KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. $(function() {
  2. var $wrap = $('#uploader'),
  3. // 图片容器
  4. $queue = $( '<ul class="filelist"></ul>' ).appendTo( $wrap.find( '.queueList' ) ),
  5. // 状态栏,包括进度和控制按钮
  6. $statusBar = $wrap.find( '.statusBar' ),
  7. // 文件总体选择信息。
  8. $info = $statusBar.find( '.info' ),
  9. // 上传按钮
  10. $upload = $wrap.find( '.uploadBtn' ),
  11. // 没选择文件之前的内容。
  12. $placeHolder = $wrap.find( '.placeholder' ),
  13. $progress = $statusBar.find( '.progress' ).hide(),
  14. // 添加的文件数量
  15. fileCount = 0,
  16. // 添加的文件总大小
  17. fileSize = 0,
  18. // 优化retina, 在retina下这个值是2
  19. ratio = window.devicePixelRatio || 1,
  20. // 缩略图大小
  21. thumbnailWidth = 110 * ratio,
  22. thumbnailHeight = 110 * ratio,
  23. // 可能有pedding, ready, uploading, confirm, done.
  24. state = 'pedding',
  25. // 所有文件的进度信息,key为file id
  26. percentages = {},
  27. // 判断浏览器是否支持图片的base64
  28. isSupportBase64 = ( function() {
  29. var data = new Image();
  30. var support = true;
  31. data.onload = data.onerror = function() {
  32. if( this.width != 1 || this.height != 1 ) {
  33. support = false;
  34. }
  35. }
  36. data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
  37. return support;
  38. } )(),
  39. // 检测是否已经安装flash,检测flash的版本
  40. flashVersion = ( function() {
  41. var version;
  42. try {
  43. version = navigator.plugins[ 'Shockwave Flash' ];
  44. version = version.description;
  45. } catch ( ex ) {
  46. try {
  47. version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
  48. } catch ( ex2 ) {
  49. version = '0.0';
  50. }
  51. }
  52. version = version.match( /\d+/g );
  53. return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );
  54. } )(),
  55. supportTransition = (function(){
  56. var s = document.createElement('p').style,
  57. r = 'transition' in s ||
  58. 'WebkitTransition' in s ||
  59. 'MozTransition' in s ||
  60. 'msTransition' in s ||
  61. 'OTransition' in s;
  62. s = null;
  63. return r;
  64. })(),
  65. // WebUploader实例
  66. uploader;
  67. if ( !WebUploader.Uploader.support('flash') && WebUploader.browser.ie ) {
  68. // flash 安装了但是版本过低。
  69. if (flashVersion) {
  70. (function(container) {
  71. window['expressinstallcallback'] = function( state ) {
  72. switch(state) {
  73. case 'Download.Cancelled':
  74. alert('您取消了更新!')
  75. break;
  76. case 'Download.Failed':
  77. alert('安装失败')
  78. break;
  79. default:
  80. alert('安装已成功,请刷新!');
  81. break;
  82. }
  83. delete window['expressinstallcallback'];
  84. };
  85. var swf = 'js/expressInstall.swf';
  86. // insert flash object
  87. var html = '<object type="application/x-shockwave-flash" data="' + swf + '" ';
  88. if (WebUploader.browser.ie) {
  89. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
  90. }
  91. html += 'width="100%" height="100%" style="outline:0">' +
  92. '<param name="movie" value="' + swf + '" />' +
  93. '<param name="wmode" value="transparent" />' +
  94. '<param name="allowscriptaccess" value="always" /></object>';
  95. container.html(html);
  96. })($wrap);
  97. // 压根就没有安转。
  98. } else {
  99. $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
  100. }
  101. return;
  102. } else if (!WebUploader.Uploader.support()) {
  103. alert( '您的浏览器不支持上传!');
  104. return;
  105. }
  106. function updateStatus() {
  107. var text = '', stats;
  108. if ( state === 'ready' ) {
  109. text = '选中' + fileCount + '张图片,共' + WebUploader.formatSize( fileSize ) + '。';
  110. } else if ( state === 'confirm' ) {
  111. stats = uploader.getStats();
  112. if ( stats.uploadFailNum ) {
  113. text = '已成功上传' + stats.successNum+ '张图片,'+
  114. stats.uploadFailNum + '张照片上传失败,<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
  115. }
  116. } else {
  117. stats = uploader.getStats();
  118. text = '共' + fileCount + '张(' + WebUploader.formatSize( fileSize ) + '),已上传' + fileCount + '张';
  119. if ( stats.uploadFailNum ) {
  120. text += ',失败' + stats.uploadFailNum + '张';
  121. }
  122. }
  123. $info.html( text );
  124. }
  125. function setState( val ) {
  126. var file, stats;
  127. if ( val === state ) {
  128. return;
  129. }
  130. $upload.removeClass( 'state-' + state );
  131. $upload.addClass( 'state-' + val );
  132. state = val;
  133. switch ( state ) {
  134. case 'pedding':
  135. $placeHolder.removeClass( 'element-invisible' );
  136. $queue.hide();
  137. $statusBar.addClass( 'element-invisible' );
  138. uploader.refresh();
  139. break;
  140. case 'ready':
  141. $placeHolder.addClass( 'element-invisible' );
  142. $( '#filePicker2' ).removeClass( 'element-invisible');
  143. $queue.show();
  144. $statusBar.removeClass('element-invisible');
  145. uploader.refresh();
  146. break;
  147. case 'uploading':
  148. $( '#filePicker2' ).addClass( 'element-invisible' );
  149. $progress.show();
  150. $upload.text( '暂停上传' );
  151. break;
  152. case 'paused':
  153. $progress.show();
  154. $upload.text( '继续上传' );
  155. break;
  156. case 'confirm':
  157. $progress.hide();
  158. $( '#filePicker2' ).removeClass( 'element-invisible' );
  159. $upload.text( '开始上传' );
  160. stats = uploader.getStats();
  161. if ( stats.successNum && !stats.uploadFailNum ) {
  162. setState( 'finish' );
  163. return;
  164. }
  165. break;
  166. case 'finish':
  167. stats = uploader.getStats();
  168. if ( stats.successNum ) {
  169. Manager.uploadComplete(uploader.fileList);
  170. // alert( '上传成功' );
  171. } else {
  172. // 没有成功的图片,重设
  173. state = 'done';
  174. location.reload();
  175. }
  176. break;
  177. }
  178. updateStatus();
  179. }
  180. // 根据ID获取file对象
  181. function getFileById(ID){
  182. var file;
  183. for(var i = 0; i < uploader.fileList.length; i++){
  184. if(ID == uploader.fileList[i].id){
  185. file = uploader.fileList[i];
  186. }
  187. };
  188. return file;
  189. }
  190. //根据ID删除文件
  191. function removeFileById( ID ) {
  192. var removeFile = getFileById(ID);
  193. uploader.removeFile(removeFile);
  194. delete percentages[ ID ];
  195. updateTotalProgress();
  196. }
  197. function updateTotalProgress() {
  198. var loaded = 0,
  199. total = 0,
  200. spans = $progress.children(),
  201. percent;
  202. $.each( percentages, function( k, v ) {
  203. total += v[ 0 ];
  204. loaded += v[ 0 ] * v[ 1 ];
  205. } );
  206. percent = total ? loaded / total : 0;
  207. spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
  208. spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
  209. updateStatus();
  210. }
  211. function webuploader(opts){
  212. var defaults = {
  213. swf: 'webuploader/Uploader.swf',
  214. server: 'fileupload.php',
  215. fileNumLimit: 10,
  216. fileSizeLimit: 50 * 1024 * 1024, // 50 M
  217. fileSingleSizeLimit: 5 * 1024 * 1024, // 5 M
  218. pick: {
  219. id: '#filePicker',
  220. label: '点击选择图片',
  221. name : 'file'
  222. },
  223. dnd: '#dndArea',
  224. paste: '#uploader',
  225. chunked: false,
  226. chunkSize: 512 * 1024,
  227. /*
  228. formData: {},
  229. accept: {
  230. title: 'Images',
  231. extensions: 'gif,jpg,jpeg,bmp,png,rar,zip',
  232. mimeTypes: 'image/*'
  233. },*/
  234. disableWidgets: 'log', // 禁止开启日志组件 by 小虎哥
  235. //禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。
  236. disableGlobalDnd: true
  237. };
  238. opts = $.extend(defaults, opts);
  239. // 实例化
  240. uploader = WebUploader.create(opts);
  241. // 拖拽时不接受 js, txt 文件。
  242. uploader.on( 'dndAccept', function( items ) {
  243. var denied = false,
  244. len = items.length,
  245. i = 0,
  246. // 修改js类型
  247. unAllowed = 'text/plain;application/javascript ';
  248. for ( ; i < len; i++ ) {
  249. // 如果在列表里面
  250. if ( ~unAllowed.indexOf( items[ i ].type ) ) {
  251. denied = true;
  252. break;
  253. }
  254. }
  255. return !denied;
  256. });
  257. // 验证大小和重复
  258. uploader.on('error', function (type) {
  259. if (type === "F_DUPLICATE") {
  260. alert("请不要选择重复文件!");
  261. return false;
  262. } else if (type === "F_EXCEED_SIZE") {
  263. /*上传大小提示 by 小虎哥*/
  264. var maxSize = opts.fileSingleSizeLimit;
  265. var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
  266. for(var i = 0; maxSize >= 1024 && i < 5; i++) {
  267. maxSize = maxSize / 1024;
  268. };
  269. maxSizeStr = Math.round(maxSize, 2) + units[i];
  270. alert("文件大小不可超过" + maxSizeStr + " 哦!换个小点的文件吧!");
  271. return false;
  272. /*end*/
  273. }
  274. });
  275. uploader.on('filesQueued', function() {
  276. uploader.sort(function( a, b ) {
  277. if ( a.name < b.name )
  278. return -1;
  279. if ( a.name > b.name )
  280. return 1;
  281. return 0;
  282. });
  283. });
  284. // 添加“添加文件”的按钮,
  285. uploader.addButton({
  286. id: '#filePicker2',
  287. label: '继续添加',
  288. name : opts.pick.name
  289. });
  290. uploader.on('ready', function() {
  291. window.uploader = uploader;
  292. });
  293. uploader.on( 'uploadSuccess', function( file,data) {
  294. $( '#'+file.id ).addClass('upload-state-done');
  295. if(data.state == 'SUCCESS'){
  296. var sLi = "";
  297. sLi += '<li class="img '+file.id+'">';
  298. sLi += '<img src="' + data.url + '" width="100" height="100" onerror="this.src=\''+__root_dir__+'/public/plugins/webuploader/images/nopic.png\'">';
  299. sLi += '<input type="hidden" name="fileurl_tmp[]" value="' + data.url + '">';
  300. sLi += '<a href="javascript:void(0);">删除</a>';
  301. sLi += '</li>';
  302. $(".fileWarp ul").append(sLi);
  303. $( '#'+file.id ).append('<div class="file-panel" style="height:0px;"><span class="cancel" data-img="'+data.url+'" onclick="Manager.del(this);">删除</span></div>');
  304. $( '#'+file.id ).hover(function(){
  305. $( '#'+file.id ).find('.file-panel').css('height','30px');
  306. },function(){
  307. $( '#'+file.id ).find('.file-panel').css('height','0px');
  308. })
  309. }else{
  310. alert(data.state);
  311. }
  312. });
  313. // 当有文件添加进来时执行,负责view的创建
  314. function addFile( file ) {
  315. uploader.fileList = uploader.fileList || [];
  316. uploader.fileList.push(file);
  317. var $li = $( '<li id="' + file.id + '">' +
  318. '<p class="title">' + file.name + '</p>' +
  319. '<p class="imgWrap"></p>'+
  320. '<p class="progress"><span></span></p>' +
  321. '</li>' ),
  322. $btns = $('<div class="file-panel">' +
  323. '<span class="cancel">删除</span>' +
  324. '<span class="rotateRight">向右旋转</span>' +
  325. '<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ),
  326. $prgress = $li.find('p.progress span'),
  327. $wrap = $li.find( 'p.imgWrap' ),
  328. $info = $('<p class="error"></p>'),
  329. showError = function( code ) {
  330. switch( code ) {
  331. case 'exceed_size':
  332. text = '文件大小超出';
  333. break;
  334. case 'interrupt':
  335. text = '上传暂停';
  336. break;
  337. default:
  338. text = '上传失败,请重试';
  339. break;
  340. }
  341. $info.text( text ).appendTo( $li );
  342. };
  343. if ( file.getStatus() === 'invalid' ) {
  344. showError( file.statusText );
  345. } else {
  346. // @todo lazyload
  347. $wrap.text( '预览中' );
  348. uploader.makeThumb( file, function( error, src ) {
  349. var img;
  350. if ( error ) {
  351. $wrap.text( '没有预览图' );
  352. return;
  353. }
  354. if( isSupportBase64 ) {
  355. img = $('<img src="'+src+'">');
  356. $wrap.empty().append( img );
  357. } else {
  358. $.ajax(eyou_basefile+"?m="+module_name+"&c=Uploadify&a=preview", {
  359. method: 'POST',
  360. data: src,
  361. dataType:'json'
  362. }).done(function( response ) {
  363. if (response.result) {
  364. img = $('<img src="'+response.result+'">');
  365. $wrap.empty().append( img );
  366. } else {
  367. $wrap.text("预览出错");
  368. }
  369. });
  370. }
  371. }, thumbnailWidth, thumbnailHeight );
  372. percentages[ file.id ] = [ file.size, 0 ];
  373. file.rotation = 0;
  374. }
  375. file.on('statuschange', function( cur, prev ) {
  376. if ( prev === 'progress' ) {
  377. $prgress.hide().width(0);
  378. } else if ( prev === 'queued' ) {
  379. $li.off( 'mouseenter mouseleave' );
  380. $btns.remove();
  381. }
  382. // 成功
  383. if ( cur === 'error' || cur === 'invalid' ) {
  384. console.log( file.statusText );
  385. showError( file.statusText );
  386. percentages[ file.id ][ 1 ] = 1;
  387. } else if ( cur === 'interrupt' ) {
  388. showError( 'interrupt' );
  389. } else if ( cur === 'queued' ) {
  390. percentages[ file.id ][ 1 ] = 0;
  391. } else if ( cur === 'progress' ) {
  392. $info.remove();
  393. $prgress.css('display', 'block');
  394. } else if ( cur === 'complete' ) {
  395. $li.append( '<span class="success"></span>' );
  396. }
  397. $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
  398. });
  399. $li.on( 'mouseenter', function() {
  400. $btns.stop().animate({height: 30});
  401. });
  402. $li.on( 'mouseleave', function() {
  403. $btns.stop().animate({height: 0});
  404. });
  405. $btns.on( 'click', 'span', function() {
  406. var index = $(this).index(),
  407. deg;
  408. switch ( index ) {
  409. case 0:
  410. uploader.removeFile( file );
  411. return;
  412. case 1:
  413. file.rotation += 90;
  414. break;
  415. case 2:
  416. file.rotation -= 90;
  417. break;
  418. }
  419. if ( supportTransition ) {
  420. deg = 'rotate(' + file.rotation + 'deg)';
  421. $wrap.css({
  422. '-webkit-transform': deg,
  423. '-mos-transform': deg,
  424. '-o-transform': deg,
  425. 'transform': deg
  426. });
  427. } else {
  428. $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
  429. // use jquery animate to rotation
  430. // $({
  431. // rotation: rotation
  432. // }).animate({
  433. // rotation: file.rotation
  434. // }, {
  435. // easing: 'linear',
  436. // step: function( now ) {
  437. // now = now * Math.PI / 180;
  438. // var cos = Math.cos( now ),
  439. // sin = Math.sin( now );
  440. // $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
  441. // }
  442. // });
  443. }
  444. });
  445. $li.appendTo( $queue );
  446. }
  447. // 负责view的销毁
  448. function removeFile( file ) {
  449. var arr = [];
  450. for(var i = 0; i < uploader.fileList.length; i++){
  451. if(file.id != uploader.fileList[i].id) arr.push(uploader.fileList[i]);
  452. };
  453. uploader.fileList = arr;
  454. var $li = $('#'+file.id);
  455. delete percentages[ file.id ];
  456. $li.off().find('.file-panel').off().end().remove();
  457. }
  458. uploader.onUploadProgress = function( file, percentage ) {
  459. var $li = $('#'+file.id),
  460. $percent = $li.find('.progress span');
  461. $percent.css( 'width', percentage * 100 + '%' );
  462. percentages[ file.id ][ 1 ] = percentage;
  463. updateTotalProgress();
  464. };
  465. uploader.onFileQueued = function( file ) {
  466. fileCount++;
  467. fileSize += file.size;
  468. if ( fileCount === 1 ) {
  469. $placeHolder.addClass( 'element-invisible' );
  470. $statusBar.show();
  471. }
  472. addFile( file );
  473. setState( 'ready' );
  474. updateTotalProgress();
  475. };
  476. uploader.onFileDequeued = function( file ) {
  477. fileCount--;
  478. fileSize -= file.size;
  479. if ( !fileCount ) {
  480. setState( 'pedding' );
  481. }
  482. removeFile( file );
  483. updateTotalProgress();
  484. };
  485. uploader.on( 'all', function( type ) {
  486. var stats;
  487. switch( type ) {
  488. case 'uploadFinished':
  489. setState( 'confirm' );
  490. break;
  491. case 'startUpload':
  492. setState( 'uploading' );
  493. break;
  494. case 'stopUpload':
  495. setState( 'paused' );
  496. break;
  497. }
  498. });
  499. uploader.onError = function( code ) {
  500. alert( '提示: ' + code );
  501. };
  502. $upload.on('click', function() {
  503. if ( $(this).hasClass( 'disabled' ) ) {
  504. return false;
  505. }
  506. if ( state === 'ready' ) {
  507. uploader.upload();
  508. } else if ( state === 'paused' ) {
  509. uploader.upload();
  510. } else if ( state === 'uploading' ) {
  511. uploader.stop();
  512. }
  513. });
  514. $info.on( 'click', '.retry', function() {
  515. uploader.retry();
  516. } );
  517. $info.on( 'click', '.ignore', function() {
  518. alert( '请检查上传配置以及上传目录写入权限' );
  519. } );
  520. $upload.addClass( 'state-' + state );
  521. updateTotalProgress();
  522. };
  523. window.Manager = {
  524. init : function(){
  525. var __self = this;
  526. var $manageArea = $('#manage_area'),$searchArea = $('#search_area');
  527. $('#upload_tab,#manage_tab,#search_tab').click(function(){
  528. var $this = $(this),
  529. $par = $this.parent(),
  530. id = $this.attr('id'),
  531. $curArea = $('div.area-checked'),
  532. $now;
  533. if($this.hasClass('checked')) return;
  534. $par.find('li.checked').removeClass('checked');
  535. $this.addClass('checked');
  536. if(id == 'upload_tab') $now = $('#upload_area');
  537. else if(id == 'manage_tab'){
  538. Manager.showList();
  539. $now = $manageArea;
  540. }else{
  541. Manager.showSearch();
  542. $now = $searchArea;
  543. }
  544. $curArea.fadeOut('fast', function(){
  545. $curArea.removeClass('area-checked');
  546. $now.fadeIn('fast').addClass('area-checked');
  547. });
  548. });
  549. $('ul.choose-btns > li.sure').click(function(){
  550. var $checkedFile = $(this).parents('div.area').find('div.file-list li.checked');
  551. if($checkedFile.length < 1){
  552. alert('请选择文件');
  553. }else {
  554. __self.sure($checkedFile);
  555. }
  556. });
  557. $('ul.choose-btns > li.cancel').click(function(){
  558. __self.cancel();
  559. });
  560. $searchArea.find('input.submit').click(function(){
  561. var key = $(this).prev('input:text').val();
  562. __self.showSearch(key);
  563. });
  564. $searchArea.find('input.key').keyup(function(e){
  565. if(e.keyCode == 13) $(this).next('input.submit').click();
  566. });
  567. },
  568. upload : function(opts){
  569. this.opts = opts, par = window.parent, type = this.opts.type;
  570. if(type == 'Images'){
  571. this.opts.accept = {
  572. title : '图片',
  573. extensions : 'gif,jpg,jpeg,bmp,png,ico,webp',
  574. mimeTypes : 'image/gif,image/jpg,image/jpeg,image/png,image/bmp,image/x-icon,image/webp'
  575. }
  576. }else if(type == 'Flash'){
  577. this.opts.accept = {
  578. title : '视频',
  579. extensions : 'flash,swf,zip',
  580. mimeTypes : 'image/*'
  581. }
  582. }else{}
  583. if(Object.prototype.toString.call(this.opts.formData) != '[object Object]') this.opts.formData = {};
  584. //this.opts.formData = $.extend(this.opts.formData, {uid : 1});
  585. if(this.opts.auto == true){
  586. $('.uploadBtn').hide();
  587. }
  588. if(this.opts.fileNumLimit == 1){
  589. $('#filePicker2').hide();
  590. }
  591. webuploader(opts);
  592. this.uploader = uploader;
  593. return this;
  594. },
  595. showList : function(){
  596. if(this.lock1) return;
  597. this.lock1 = true;
  598. this.showFiles({type : this.opts.type}, $('#file_all_list'))
  599. },
  600. showSearch : function(key){
  601. if(this.lock2) return;
  602. this.lock2 = true;
  603. var data = {};
  604. if(key) data.key = key;
  605. data.type = this.opts.type;
  606. this.showFiles(data, $('#file_search_list'))
  607. },
  608. //显示文件列表
  609. showFiles : function(data, $container){
  610. var __self = this;
  611. $container.empty().parents('div.area').addClass('loading');
  612. data = typeof data == 'object' && data != null ? data : {};
  613. data = $.extend(data, this.opts.formData);
  614. $.ajax({
  615. url : __self.opts.filelistPah,
  616. data : data,
  617. dataType : 'json',
  618. success : function(data){
  619. var $html = __self.createFile(data);
  620. if(typeof $html == 'string') $container.append($html);
  621. else{
  622. for(var i = 0; i < $html.length; i++) $container.append($html[i]);
  623. }
  624. },
  625. complete : function(){
  626. __self.lock1 = false;
  627. __self.lock2 = false;
  628. $container.parents('div.area').removeClass('loading');
  629. }
  630. });
  631. },
  632. //生成单个文件
  633. createFile : function(data){
  634. var __self = this, str = '<li class="nofile">没有文件</li>';
  635. if(data && data.list && data.list.length > 0){
  636. var arr = [], li, i = 0, t, file, ext;
  637. for(; i < data.list.length; i++){
  638. t = data.list[i];
  639. ext = t.name.split('.');
  640. ext = ext[ext.length - 1];
  641. file = '<div class="img" title="' + t.name + '"><img width="100%" src="' + t.url + '" /><span class="icon"></span></div>';
  642. if(!/png|jpg|jpeg|gif|bmp/.test(ext)) file = '<div class="img file-global file-' + ext + '" title="' + t.name + '"><span class="icon"></span></div>';
  643. $li = $('<li class="file"><div class="file-panel"><span class="cancel">删除</span></div>' + file + '<div class="desc">' + t.name + '</div></li>');
  644. $li.click(function(){
  645. __self.checkFile($(this));
  646. }).data('file', {name : t.name, url : t.url, mtime : t.mtime, list : data.list});
  647. $li.find('span.cancel').click(function(){
  648. __self.delFile($(this).parents('li'));
  649. return false;
  650. });
  651. $li.find('div.img').dblclick(function(){
  652. __self.sure($(this).parent());
  653. });
  654. arr.push($li);
  655. }
  656. return arr;
  657. }
  658. return str;
  659. },
  660. checkFile : function($file){
  661. if(this.$curFile) this.cancelFile(this.$curFile);
  662. $file.addClass('checked');
  663. this.$curFile = $file;
  664. },
  665. delFile : function($file){
  666. if(!confirm('确定删除吗?')) return false;
  667. var file = $file.data('file');
  668. $file.find('div.file-panel').css('display', 'none');
  669. var data = {url : file.url, name : file.name, mtime : file.mtime, action : 'del'};
  670. data = $.extend(data, this.opts.formData);
  671. $.ajax({
  672. url : this.opts.delPath,
  673. data : data,
  674. type : 'POST',
  675. success : function(data){
  676. if(data == 1){
  677. $file.fadeOut(function(){
  678. $(this).remove();
  679. });
  680. }else{
  681. alert('删除失败');
  682. }
  683. },
  684. complete : function(){
  685. $file.find('div.file-panel').css('display', 'block');
  686. }
  687. });
  688. },
  689. cancelFile : function($file){
  690. if(!$file) $file = this.$curFile;
  691. if($file) $file.removeClass('checked');
  692. },
  693. //选中文件
  694. sure : function($file){
  695. var data = $file.data('file');
  696. var sLi = "";
  697. sLi += '<li class="img">';
  698. sLi += '<img src="' + data.url + '" width="100" height="100" onerror="this.src=\''+__root_dir__+'/public/plugins/webuploader/images/nopic.png\'">';
  699. sLi += '<input type="hidden" name="fileurl_tmp[]" value="' + data.url + '">';
  700. sLi += '<a href="javascript:void(0);">删除</a>';
  701. sLi += '</li>';
  702. $(".fileWarp ul").append(sLi);
  703. $(".statusBar .saveBtn").trigger("click");
  704. },
  705. cancel : function(){
  706. window.parent.layer.closeAll();
  707. },
  708. uploadComplete : function(list){
  709. console.log(list)
  710. },
  711. del:function(obj){
  712. if(!confirm('确定删除吗?')) return false;
  713. $.post(eyou_basefile+"?m="+module_name+"&c=Uploadify&a=delupload",{action:"del", filename:$(obj).attr('data-img')},function(res){
  714. if(res == 1){
  715. var id = $(obj).parents('.state-complete').attr('id');
  716. removeFileById(id);
  717. $('.'+id).remove();
  718. }else{
  719. alert("删除失败");
  720. }
  721. }
  722. );
  723. }
  724. };
  725. Manager.init();
  726. });