webuploader.html 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. <include file="public@header"/>
  2. <link rel="stylesheet" type="text/css" href="__ROOT__/static/js/webuploader/webuploader.css">
  3. <link rel="stylesheet" type="text/css" href="__ROOT__/static/js/webuploader/image-upload/style.css">
  4. <style>
  5. .state-complete .progress {
  6. display: none;
  7. }
  8. #uploader .statusBar .progress {
  9. vertical-align: middle;
  10. margin-bottom: 0;
  11. }
  12. #uploader .statusBar{
  13. padding: 0 15px;
  14. }
  15. #uploader .statusBar .info {
  16. line-height: 1.2 !important;
  17. vertical-align: middle;
  18. }
  19. </style>
  20. </head>
  21. <body class="body_none">
  22. <div class="wrap " style="padding:5px;">
  23. <ul class="nav nav-tabs">
  24. <li class="{$tab=='local'?'active':''}"><a href="#wrapper" data-toggle="tab">上传文件</a></li>
  25. <!-- <li class="{$tab=='url'?'active':''}"><a href="#B" data-toggle="tab">网络文件</a></li>
  26. <notempty name="has_cloud_storage">
  27. <php>
  28. $url_params=input('param.');
  29. $url_params['tab']='cloud';
  30. </php>
  31. <li><a href="{:url('user/Asset/webuploader',$url_params)}">上传到云存储</a></li>
  32. </notempty> -->
  33. <!--<li class=""><a href="#explorer" data-toggle="tab">文件管理</a></li>-->
  34. </ul>
  35. <div class="tabbable">
  36. <div class="tab-content ">
  37. <div class="tab-pane active" id="wrapper">
  38. <div id="container">
  39. <!--头部,相册选择和格式选择-->
  40. <div id="uploader">
  41. <div class="queueList">
  42. <div id="dndArea" class="placeholder">
  43. <div id="filePicker"></div>
  44. <p>或将文件拖到这里,单次最多可选{$max_files}个文件</p>
  45. </div>
  46. </div>
  47. <div class="statusBar" style="display:none;">
  48. <div class="progress">
  49. <span class="text">0%</span>
  50. <span class="percentage"></span>
  51. </div>
  52. <div class="info"></div>
  53. <div class="btns">
  54. <div id="filePicker2"></div>
  55. <div class="uploadBtn">开始上传</div>
  56. </div>
  57. </div>
  58. </div>
  59. </div>
  60. </div>
  61. <div class="tab-pane" id="B"> 请输入网络地址
  62. <div class="bk3"></div>
  63. <input type="hidden" id="img_name" value="">
  64. <input type="text" id="info" name="info[filename]" class="input form-control" value=""
  65. placeholder="http://">
  66. </div>
  67. <div class="tab-pane" id="explorer">
  68. <div class="bk3"></div>
  69. </div>
  70. </div>
  71. </div>
  72. </div>
  73. <script src="__ROOT__/static/js/admin.js"></script>
  74. <script src="__ROOT__/static/js/webuploader/webuploader.min.js"></script>
  75. <script type="text/javascript">
  76. var httpUrl = "{:cmf_get_asset_url('')}";
  77. function get_selected_files() {
  78. var files = [];
  79. var idPre = 'id' + new Date().getTime();
  80. if (jQuery("#wrapper").is(":hidden")) {
  81. var file = new Object();
  82. console.log("get_selected_files");
  83. console.log(file);
  84. file.id = idPre + '1';
  85. file.filepath = jQuery("#info").val();
  86. file.preview_url = file.filepath;
  87. file.url = file.filepath;
  88. file.name = "";//jQuery(".filelist li .title").eq(i).html();
  89. files.push(file);
  90. } else {
  91. var number = jQuery(".filelist li").size();
  92. for (var i = 0; i < number; i++) {
  93. var file = new Object();
  94. var $file = jQuery(".filelist li").eq(i);
  95. file.id = idPre + i;
  96. file.filepath = $file.data("filepath");
  97. file.preview_url = $file.data("preview_url");//httpUrl+file.filepath;
  98. file.url = $file.data("url");
  99. file.name = $file.data("name");
  100. if (file.url == undefined) {
  101. continue;
  102. } else {
  103. files.push(file);
  104. }
  105. }
  106. }
  107. return files;
  108. }
  109. var multi = {$multi};//是否允许同时选多个文件
  110. var maxFiles = {$max_files};//允许上传多少文件
  111. var fileErrorMsg = {};
  112. (function ($) {
  113. // 当domReady的时候开始初始化
  114. $(function () {
  115. var $wrap = $('#uploader'),
  116. // 图片容器
  117. $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList')),
  118. // 状态栏,包括进度和控制按钮
  119. $statusBar = $wrap.find('.statusBar'),
  120. // 文件总体选择信息。
  121. $info = $statusBar.find('.info'),
  122. // 上传按钮
  123. $upload = $wrap.find('.uploadBtn').hide(),
  124. // 没选择文件之前的内容。
  125. $placeHolder = $wrap.find('.placeholder'),
  126. $progress = $statusBar.find('.progress').hide(),
  127. // 添加的文件数量
  128. fileCount = 0,
  129. // 添加的文件总大小
  130. fileSize = 0,
  131. // 优化retina, 在retina下这个值是2
  132. ratio = window.devicePixelRatio || 1,
  133. // 缩略图大小
  134. thumbnailWidth = 110 * ratio,
  135. thumbnailHeight = 110 * ratio,
  136. // 可能有pedding, ready, uploading, confirm, done.
  137. state = 'pedding',
  138. // 所有文件的进度信息,key为file id
  139. percentages = {},
  140. // 判断浏览器是否支持图片的base64
  141. isSupportBase64 = (function () {
  142. var data = new Image();
  143. var support = true;
  144. data.onload = data.onerror = function () {
  145. if (this.width != 1 || this.height != 1) {
  146. support = false;
  147. }
  148. }
  149. data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
  150. return support;
  151. })(),
  152. // 检测是否已经安装flash,检测flash的版本
  153. flashVersion = (function () {
  154. var version;
  155. try {
  156. version = navigator.plugins['Shockwave Flash'];
  157. version = version.description;
  158. } catch (ex) {
  159. try {
  160. version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
  161. } catch (ex2) {
  162. version = '0.0';
  163. }
  164. }
  165. version = version.match(/\d+/g);
  166. return parseFloat(version[0] + '.' + version[1], 10);
  167. })(),
  168. supportTransition = (function () {
  169. var s = document.createElement('p').style,
  170. r = 'transition' in s ||
  171. 'WebkitTransition' in s ||
  172. 'MozTransition' in s ||
  173. 'msTransition' in s ||
  174. 'OTransition' in s;
  175. s = null;
  176. return r;
  177. })(),
  178. // WebUploader实例
  179. uploader;
  180. if (!WebUploader.Uploader.support('flash') && WebUploader.browser.ie) {
  181. // flash 安装了但是版本过低。
  182. if (flashVersion) {
  183. (function (container) {
  184. window['expressinstallcallback'] = function (state) {
  185. switch (state) {
  186. case 'Download.Cancelled':
  187. alert('您取消了更新!')
  188. break;
  189. case 'Download.Failed':
  190. alert('安装失败')
  191. break;
  192. default:
  193. alert('安装已成功,请刷新!');
  194. break;
  195. }
  196. delete window['expressinstallcallback'];
  197. };
  198. var swf = './expressInstall.swf';
  199. // insert flash object
  200. var html = '<object type="application/' +
  201. 'x-shockwave-flash" data="' + swf + '" ';
  202. if (WebUploader.browser.ie) {
  203. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
  204. }
  205. html += 'width="100%" height="100%" style="outline:0">' +
  206. '<param name="movie" value="' + swf + '" />' +
  207. '<param name="wmode" value="transparent" />' +
  208. '<param name="allowscriptaccess" value="always" />' +
  209. '</object>';
  210. container.html(html);
  211. })($wrap);
  212. // 压根就没有安转。
  213. } else {
  214. $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>');
  215. }
  216. return;
  217. } else if (!WebUploader.Uploader.support()) {
  218. alert('Web Uploader 不支持您的浏览器!');
  219. return;
  220. }
  221. // 实例化
  222. uploader = WebUploader.create({
  223. pick: {
  224. id: '#filePicker',
  225. label: '点击选择文件',
  226. multiple: multi,
  227. },
  228. timeout: 0,
  229. formData: {
  230. app: '{$app}',
  231. filetype: '{$filetype}'
  232. },
  233. accept: {
  234. extensions: '{$extensions}'
  235. },
  236. dnd: '#dndArea',
  237. paste: '#uploader',
  238. swf: GV.WEB_ROOT + GV.JS_ROOT + 'webuploader/Uploader.swf',
  239. chunked: true,//开启分片
  240. auto: true,
  241. chunkSize: {$chunk_size} * 1024,// 单位B
  242. compress: false,
  243. server: "{:url('user/asset/webuploader')}?_ajax=1",
  244. // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。
  245. disableGlobalDnd: true,
  246. fileNumLimit: maxFiles,
  247. runtimeOrder: 'html5,flash',
  248. //fileSizeLimit: 200 * 1024 * 1024, // 200 M
  249. fileSingleSizeLimit: {$upload_max_filesize} // 单位B
  250. });
  251. // 拖拽时不接受 js, txt 文件。
  252. uploader.on('dndAccept', function (items) {
  253. var denied = false,
  254. len = items.length,
  255. i = 0,
  256. // 修改js类型
  257. unAllowed = 'text/plain;application/javascript ';
  258. for (; i < len; i++) {
  259. // 如果在列表里面
  260. if (~unAllowed.indexOf(items[i].type)) {
  261. denied = true;
  262. break;
  263. }
  264. }
  265. return !denied;
  266. });
  267. // uploader.on('filesQueued', function() {
  268. // uploader.sort(function( a, b ) {
  269. // if ( a.name < b.name )
  270. // return -1;
  271. // if ( a.name > b.name )
  272. // return 1;
  273. // return 0;
  274. // });
  275. // });
  276. if (maxFiles > 1) {
  277. // 添加“添加文件”的按钮,
  278. uploader.addButton({
  279. id: '#filePicker2',
  280. label: '继续添加'
  281. });
  282. }
  283. uploader.on('ready', function () {
  284. window.uploader = uploader;
  285. });
  286. // 当有文件添加进来时执行,负责view的创建
  287. function addFile(file) {
  288. var $li = $('<li id="' + file.id + '">' +
  289. '<p class="title">' + file.name + '</p>' +
  290. '<p class="imgWrap"></p>' +
  291. '<p class="progress"><span></span></p>' +
  292. '</li>'),
  293. $btns = $('<div class="file-panel">' +
  294. '<span class="cancel">删除</span>' +
  295. '<span class="rotateRight">向右旋转</span>' +
  296. '<span class="rotateLeft">向左旋转</span></div>').appendTo($li),
  297. $prgress = $li.find('p.progress span'),
  298. $wrap = $li.find('p.imgWrap'),
  299. $info = $('<p class="error"></p>'),
  300. showError = function (code) {
  301. switch (code) {
  302. case 'exceed_size':
  303. text = '文件大小超出';
  304. break;
  305. case 'interrupt':
  306. text = '上传暂停';
  307. break;
  308. default:
  309. text = '上传失败,请重试';
  310. break;
  311. }
  312. $info.text(text).appendTo($li);
  313. };
  314. if (file.getStatus() === 'invalid') {
  315. showError(file.statusText);
  316. } else {
  317. // @todo lazyload
  318. $wrap.text('预览中');
  319. uploader.makeThumb(file, function (error, src) {
  320. var img;
  321. if (error) {
  322. $wrap.text('不能预览');
  323. return;
  324. }
  325. if (isSupportBase64) {
  326. img = $('<img src="' + src + '">');
  327. $wrap.empty().append(img);
  328. } else {
  329. $.ajax('../../server/preview.php', {
  330. method: 'POST',
  331. data: src,
  332. dataType: 'json'
  333. }).done(function (response) {
  334. if (response.result) {
  335. img = $('<img src="' + response.result + '">');
  336. $wrap.empty().append(img);
  337. } else {
  338. $wrap.text("预览出错");
  339. }
  340. });
  341. }
  342. }, thumbnailWidth, thumbnailHeight);
  343. percentages[file.id] = [file.size, 0];
  344. file.rotation = 0;
  345. }
  346. file.on('statuschange', function (cur, prev) {
  347. if (prev === 'progress') {
  348. $prgress.hide().width(0);
  349. } else if (prev === 'queued') {
  350. $li.off('mouseenter mouseleave');
  351. $btns.remove();
  352. }
  353. // 成功
  354. if (cur === 'error' || cur === 'invalid') {
  355. <!-- console.log(file.statusText); -->
  356. showError(file.statusText);
  357. percentages[file.id][1] = 1;
  358. } else if (cur === 'interrupt') {
  359. showError('interrupt');
  360. } else if (cur === 'queued') {
  361. percentages[file.id][1] = 0;
  362. } else if (cur === 'progress') {
  363. $info.remove();
  364. $prgress.css('display', 'block');
  365. } else if (cur === 'complete') {
  366. $li.append('<span class="success"></span>');
  367. }
  368. $li.removeClass('state-' + prev).addClass('state-' + cur);
  369. });
  370. $li.on('mouseenter', function () {
  371. $btns.stop().animate({height: 30});
  372. });
  373. $li.on('mouseleave', function () {
  374. $btns.stop().animate({height: 0});
  375. });
  376. $btns.on('click', 'span', function () {
  377. var index = $(this).index(),
  378. deg;
  379. switch (index) {
  380. case 0:
  381. uploader.removeFile(file);
  382. return;
  383. case 1:
  384. file.rotation += 90;
  385. break;
  386. case 2:
  387. file.rotation -= 90;
  388. break;
  389. }
  390. if (supportTransition) {
  391. deg = 'rotate(' + file.rotation + 'deg)';
  392. $wrap.css({
  393. '-webkit-transform': deg,
  394. '-mos-transform': deg,
  395. '-o-transform': deg,
  396. 'transform': deg
  397. });
  398. } else {
  399. $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
  400. // use jquery animate to rotation
  401. // $({
  402. // rotation: rotation
  403. // }).animate({
  404. // rotation: file.rotation
  405. // }, {
  406. // easing: 'linear',
  407. // step: function( now ) {
  408. // now = now * Math.PI / 180;
  409. // var cos = Math.cos( now ),
  410. // sin = Math.sin( now );
  411. // $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
  412. // }
  413. // });
  414. }
  415. });
  416. $li.appendTo($queue);
  417. }
  418. // 负责view的销毁
  419. function removeFile(file) {
  420. var $li = $('#' + file.id);
  421. delete percentages[file.id];
  422. updateTotalProgress();
  423. $li.off().find('.file-panel').off().end().remove();
  424. }
  425. function updateTotalProgress() {
  426. var loaded = 0,
  427. total = 0,
  428. spans = $progress.children(),
  429. percent;
  430. $.each(percentages, function (k, v) {
  431. total += v[0];
  432. loaded += v[0] * v[1];
  433. });
  434. percent = total ? loaded / total : 0;
  435. spans.eq(0).text(Math.round(percent * 100) + '%');
  436. spans.eq(1).css('width', Math.round(percent * 100) + '%');
  437. updateStatus();
  438. }
  439. function updateStatus() {
  440. var text = '', stats;
  441. if (state === 'ready') {
  442. text = '选中' + fileCount + '个文件,共' +
  443. WebUploader.formatSize(fileSize) + '。';
  444. } else if (state === 'confirm') {
  445. stats = uploader.getStats();
  446. if (stats.uploadFailNum) {
  447. text = '已成功上传' + stats.successNum + '个文件,' +
  448. stats.uploadFailNum + '个文件上传失败,<a class="retry" href="#">重新上传</a>失败文件或<a class="ignore" href="#">忽略</a>'
  449. }
  450. } else {
  451. stats = uploader.getStats();
  452. text = '共' + fileCount + '个文件(' +
  453. WebUploader.formatSize(fileSize) +
  454. '),已上传' + stats.successNum + '个';
  455. if (stats.uploadFailNum) {
  456. text += ',失败' + stats.uploadFailNum + '个';
  457. }
  458. if (stats.progressNum > 0) {
  459. text += '<br>上传期间请不要关闭对话框';
  460. }
  461. }
  462. $info.html(text);
  463. }
  464. function setState(val) {
  465. var file, stats;
  466. if (val === state) {
  467. return;
  468. }
  469. $upload.removeClass('state-' + state);
  470. $upload.addClass('state-' + val);
  471. state = val;
  472. switch (state) {
  473. case 'pedding':
  474. $placeHolder.removeClass('element-invisible');
  475. $queue.hide();
  476. $statusBar.addClass('element-invisible');
  477. uploader.refresh();
  478. break;
  479. case 'ready':
  480. $placeHolder.addClass('element-invisible');
  481. $('#filePicker2').removeClass('element-invisible');
  482. $queue.show();
  483. $statusBar.removeClass('element-invisible');
  484. uploader.refresh();
  485. break;
  486. case 'uploading':
  487. $('#filePicker2').addClass('element-invisible');
  488. $progress.show();
  489. $upload.text('暂停上传');
  490. break;
  491. case 'paused':
  492. $progress.show();
  493. $upload.text('继续上传');
  494. break;
  495. case 'confirm':
  496. $progress.hide();
  497. $('#filePicker2').removeClass('element-invisible');
  498. $upload.text('开始上传');
  499. stats = uploader.getStats();
  500. if (stats.successNum && !stats.uploadFailNum) {
  501. setState('finish');
  502. return;
  503. }
  504. break;
  505. case 'finish':
  506. stats = uploader.getStats();
  507. if (stats.successNum) {
  508. //alert( '上传成功' );
  509. } else {
  510. // 没有成功的图片,重设
  511. state = 'done';
  512. location.reload();
  513. }
  514. break;
  515. }
  516. updateStatus();
  517. }
  518. uploader.onUploadProgress = function (file, percentage) {
  519. var $li = $('#' + file.id),
  520. $percent = $li.find('.progress span');
  521. $percent.css('width', percentage * 100 + '%');
  522. percentages[file.id][1] = percentage;
  523. updateTotalProgress();
  524. };
  525. uploader.onFileQueued = function (file) {
  526. fileCount++;
  527. fileSize += file.size;
  528. if (fileCount === 1) {
  529. $placeHolder.addClass('element-invisible');
  530. $statusBar.show();
  531. }
  532. addFile(file);
  533. setState('ready');
  534. updateTotalProgress();
  535. };
  536. uploader.onFileDequeued = function (file) {
  537. fileCount--;
  538. fileSize -= file.size;
  539. if (!fileCount) {
  540. setState('pedding');
  541. }
  542. removeFile(file);
  543. updateTotalProgress();
  544. };
  545. uploader.on('all', function (type, file, msg) {
  546. var stats;
  547. switch (type) {
  548. case 'uploadSuccess':
  549. // console.log(file);
  550. // console.log(msg);
  551. if (msg._raw != '') {
  552. var $file = jQuery("#" + file.id);
  553. $file.data("filepath", msg.data.filepath);
  554. $file.data("name", msg.data.name);
  555. $file.data("url", msg.data.url);
  556. $file.data("preview_url", msg.data.preview_url);
  557. }
  558. break;
  559. case 'uploadFinished':
  560. setState('confirm');
  561. break;
  562. case 'startUpload':
  563. setState('uploading');
  564. break;
  565. case 'stopUpload':
  566. setState('paused');
  567. break;
  568. }
  569. });
  570. uploader.on("uploadAccept", function (object, ret) {
  571. console.log(object);
  572. console.log(ret);
  573. if (ret.code == 0) {
  574. fileErrorMsg[object.file.id] = ret.msg;
  575. return false;
  576. }
  577. return true;
  578. });
  579. uploader.on('uploadError', function (file, reason) {
  580. console.log(file.id);
  581. console.log(reason);
  582. if (reason == 'server') {
  583. $('#' + file.id).find('p.error').text(fileErrorMsg[file.id]);
  584. }
  585. });
  586. uploader.onError = function (code) {
  587. switch (code) {
  588. case "Q_TYPE_DENIED":
  589. code = "文件类型错误!";
  590. break;
  591. case "Q_EXCEED_NUM_LIMIT":
  592. code = "最多只能上传" + maxFiles + '个文件';
  593. break;
  594. case "F_DUPLICATE":
  595. code = "文件重复添加!";
  596. break;
  597. case "F_EXCEED_SIZE":
  598. code = "您需要选择小于{$upload_max_filesize_mb}M的文件!";
  599. break;
  600. }
  601. alert(code);
  602. };
  603. $upload.on('click', function () {
  604. if ($(this).hasClass('disabled')) {
  605. return false;
  606. }
  607. if (state === 'ready') {
  608. uploader.upload();
  609. } else if (state === 'paused') {
  610. uploader.upload();
  611. } else if (state === 'uploading') {
  612. uploader.stop();
  613. }
  614. });
  615. $info.on('click', '.retry', function () {
  616. uploader.retry();
  617. });
  618. $info.on('click', '.ignore', function () {
  619. alert('todo');
  620. });
  621. $upload.addClass('state-' + state);
  622. updateTotalProgress();
  623. });
  624. })(jQuery);
  625. </script>
  626. </body>
  627. </html>