addons.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. define([], function () {
  2. if (typeof Config.upload.storage !== 'undefined' && Config.upload.storage === 'alioss') {
  3. require(['upload'], function (Upload) {
  4. //获取文件MD5值
  5. var getFileMd5 = function (file, cb) {
  6. //如果savekey中未检测到md5,则无需获取文件md5,直接返回upload的uuid
  7. if (!Config.upload.savekey.match(/\{(file)?md5\}/)) {
  8. cb && cb(file.upload.uuid);
  9. return;
  10. }
  11. require(['../addons/alioss/js/spark'], function (SparkMD5) {
  12. var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
  13. chunkSize = 10 * 1024 * 1024,
  14. chunks = Math.ceil(file.size / chunkSize),
  15. currentChunk = 0,
  16. spark = new SparkMD5.ArrayBuffer(),
  17. fileReader = new FileReader();
  18. fileReader.onload = function (e) {
  19. spark.append(e.target.result);
  20. currentChunk++;
  21. if (currentChunk < chunks) {
  22. loadNext();
  23. } else {
  24. cb && cb(spark.end());
  25. }
  26. };
  27. fileReader.onerror = function () {
  28. console.warn('文件读取错误');
  29. };
  30. function loadNext() {
  31. var start = currentChunk * chunkSize,
  32. end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
  33. fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  34. }
  35. loadNext();
  36. });
  37. };
  38. var _onInit = Upload.events.onInit;
  39. //初始化中完成判断
  40. Upload.events.onInit = function () {
  41. _onInit.apply(this, Array.prototype.slice.apply(arguments));
  42. //如果上传接口不是阿里OSS,则不处理
  43. if (this.options.url !== Config.upload.uploadurl) {
  44. return;
  45. }
  46. $.extend(this.options, {
  47. //关闭自动处理队列功能
  48. autoQueue: false,
  49. params: function (files, xhr, chunk) {
  50. var params = Config.upload.multipart;
  51. if (chunk) {
  52. return $.extend({}, params, {
  53. filesize: chunk.file.size,
  54. filename: chunk.file.name,
  55. chunkid: chunk.file.upload.uuid,
  56. chunkindex: chunk.index,
  57. chunkcount: chunk.file.upload.totalChunkCount,
  58. chunksize: this.options.chunkSize,
  59. chunkfilesize: chunk.dataBlock.data.size,
  60. width: chunk.file.width || 0,
  61. height: chunk.file.height || 0,
  62. type: chunk.file.type,
  63. uploadId: chunk.file.uploadId,
  64. key: chunk.file.key,
  65. });
  66. } else {
  67. params = $.extend({}, params, files[0].params);
  68. params.category = files[0].category || '';
  69. }
  70. return params;
  71. },
  72. chunkSuccess: function (chunk, file, response) {
  73. var etag = chunk.xhr.getResponseHeader("ETag").replace(/(^")|("$)/g, '');
  74. file.etags = file.etags ? file.etags : [];
  75. file.etags[chunk.index] = etag;
  76. },
  77. chunksUploaded: function (file, done) {
  78. var that = this;
  79. Fast.api.ajax({
  80. url: "/addons/alioss/index/upload",
  81. data: {
  82. action: 'merge',
  83. filesize: file.size,
  84. filename: file.name,
  85. chunkid: file.upload.uuid,
  86. chunkcount: file.upload.totalChunkCount,
  87. md5: file.md5,
  88. key: file.key,
  89. uploadId: file.uploadId,
  90. etags: file.etags,
  91. category: file.category || '',
  92. aliosstoken: Config.upload.multipart.aliosstoken,
  93. },
  94. }, function (data, ret) {
  95. done(JSON.stringify(ret));
  96. return false;
  97. }, function (data, ret) {
  98. file.accepted = false;
  99. that._errorProcessing([file], ret.msg);
  100. return false;
  101. });
  102. },
  103. });
  104. var _success = this.options.success;
  105. //先移除已有的事件
  106. this.off("success", _success).on("success", function (file, response) {
  107. var ret = {code: 0, msg: response};
  108. try {
  109. if (response) {
  110. ret = typeof response === 'string' ? JSON.parse(response) : response;
  111. }
  112. if (file.xhr.status === 200) {
  113. if (Config.upload.uploadmode === 'client') {
  114. ret = {code: 1, data: {url: '/' + file.key}};
  115. var url = ret.data.url || '';
  116. Fast.api.ajax({
  117. url: "/addons/alioss/index/notify",
  118. data: {name: file.name, url: url, md5: file.md5, size: file.size, width: file.width || 0, height: file.height || 0, type: file.type, category: file.category || '', aliosstoken: Config.upload.multipart.aliosstoken}
  119. }, function () {
  120. return false;
  121. }, function () {
  122. return false;
  123. });
  124. }
  125. } else {
  126. console.error(file.xhr);
  127. }
  128. } catch (e) {
  129. console.error(e);
  130. }
  131. _success.call(this, file, ret);
  132. });
  133. this.on("addedfile", function (file) {
  134. var that = this;
  135. setTimeout(function () {
  136. if (file.status === 'error') {
  137. return;
  138. }
  139. getFileMd5(file, function (md5) {
  140. var chunk = that.options.chunking && file.size > that.options.chunkSize ? 1 : 0;
  141. var params = $(that.element).data("params") || {};
  142. var category = typeof params.category !== 'undefined' ? params.category : ($(that.element).data("category") || '');
  143. category = typeof category === 'function' ? category.call(that, file) : category;
  144. Fast.api.ajax({
  145. url: "/addons/alioss/index/params",
  146. data: {method: 'POST', category: category, md5: md5, name: file.name, type: file.type, size: file.size, chunk: chunk, chunksize: that.options.chunkSize, aliosstoken: Config.upload.multipart.aliosstoken},
  147. }, function (data) {
  148. file.md5 = md5;
  149. file.id = data.id;
  150. file.key = data.key;
  151. file.date = data.date;
  152. file.uploadId = data.uploadId;
  153. file.policy = data.policy;
  154. file.signature = data.signature;
  155. file.partsAuthorization = data.partsAuthorization;
  156. file.params = data;
  157. file.category = category;
  158. if (file.status != 'error') {
  159. //开始上传
  160. that.enqueueFile(file);
  161. } else {
  162. that.removeFile(file);
  163. }
  164. return false;
  165. }, function () {
  166. that.removeFile(file);
  167. });
  168. });
  169. }, 0);
  170. });
  171. if (Config.upload.uploadmode === 'client') {
  172. var _method = this.options.method;
  173. var _url = this.options.url;
  174. this.options.method = function (files) {
  175. if (files[0].upload.chunked) {
  176. var chunk = null;
  177. files[0].upload.chunks.forEach(function (item) {
  178. if (item.status === 'uploading') {
  179. chunk = item;
  180. }
  181. });
  182. if (!chunk) {
  183. return "POST";
  184. } else {
  185. return "PUT";
  186. }
  187. }
  188. return _method;
  189. };
  190. this.options.url = function (files) {
  191. if (files[0].upload.chunked) {
  192. var chunk = null;
  193. files[0].upload.chunks.forEach(function (item) {
  194. if (item.status === 'uploading') {
  195. chunk = item;
  196. }
  197. });
  198. var index = chunk.dataBlock.chunkIndex;
  199. // debugger;
  200. this.options.headers = {"Authorization": "OSS " + files[0]['id'] + ":" + files[0]['partsAuthorization'][index], "x-oss-date": files[0]['date']};
  201. if (!chunk) {
  202. return Config.upload.uploadurl + "/" + files[0].key + "?uploadId=" + files[0].uploadId;
  203. } else {
  204. return Config.upload.uploadurl + "/" + files[0].key + "?partNumber=" + (index + 1) + "&uploadId=" + files[0].uploadId;
  205. }
  206. }
  207. return _url;
  208. };
  209. this.on("sending", function (file, xhr, formData) {
  210. var that = this;
  211. if (file.upload.chunked) {
  212. var _send = xhr.send;
  213. xhr.send = function () {
  214. var chunk = null;
  215. file.upload.chunks.forEach(function (item) {
  216. if (item.status == 'uploading') {
  217. chunk = item;
  218. }
  219. });
  220. if (chunk) {
  221. _send.call(xhr, chunk.dataBlock.data);
  222. }
  223. };
  224. }
  225. });
  226. }
  227. };
  228. });
  229. }
  230. require(['fast', 'layer'], function (Fast, Layer) {
  231. var _fastOpen = Fast.api.open;
  232. Fast.api.open = function (url, title, options) {
  233. options = options || {};
  234. options.area = Config.betterform.area;
  235. options.offset = Config.betterform.offset;
  236. options.anim = Config.betterform.anim;
  237. options.shadeClose = Config.betterform.shadeClose;
  238. options.shade = Config.betterform.shade;
  239. return _fastOpen(url, title, options);
  240. };
  241. if (isNaN(Config.betterform.anim)) {
  242. var _layerOpen = Layer.open;
  243. Layer.open = function (options) {
  244. var classNameArr = {slideDown: "layer-anim-slide-down", slideLeft: "layer-anim-slide-left", slideUp: "layer-anim-slide-up", slideRight: "layer-anim-slide-right"};
  245. var animClass = "layer-anim " + classNameArr[options.anim] || "layer-anim-fadein";
  246. var index = _layerOpen(options);
  247. var layero = $('#layui-layer' + index);
  248. layero.addClass(classNameArr[options.anim] + "-custom");
  249. layero.addClass(animClass).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
  250. $(this).removeClass(animClass);
  251. });
  252. return index;
  253. }
  254. }
  255. });
  256. require.config({
  257. paths: {
  258. 'nkeditor': '../addons/nkeditor/js/customplugin',
  259. 'nkeditor-core': '../addons/nkeditor/nkeditor',
  260. 'nkeditor-lang': '../addons/nkeditor/lang/zh-CN',
  261. },
  262. shim: {
  263. 'nkeditor': {
  264. deps: [
  265. 'nkeditor-core',
  266. 'nkeditor-lang'
  267. ]
  268. },
  269. 'nkeditor-core': {
  270. deps: [
  271. 'css!../addons/nkeditor/themes/black/editor.min.css',
  272. 'css!../addons/nkeditor/css/common.css'
  273. ],
  274. exports: 'window.KindEditor'
  275. },
  276. 'nkeditor-lang': {
  277. deps: [
  278. 'nkeditor-core'
  279. ]
  280. }
  281. }
  282. });
  283. require(['form'], function (Form) {
  284. var _bindevent = Form.events.bindevent;
  285. Form.events.bindevent = function (form) {
  286. _bindevent.apply(this, [form]);
  287. if ($(Config.nkeditor.classname || '.editor', form).length > 0) {
  288. require(['nkeditor', 'upload'], function (Nkeditor, Upload) {
  289. var getFileFromBase64, uploadFiles;
  290. uploadFiles = async function (files) {
  291. var self = this;
  292. for (var i = 0; i < files.length; i++) {
  293. try {
  294. await new Promise((resolve) => {
  295. var url, html, file;
  296. file = files[i];
  297. Upload.api.send(file, function (data) {
  298. url = Config.nkeditor.fullmode ? Fast.api.cdnurl(data.url, true) : Fast.api.cdnurl(data.url);
  299. if (file.type.indexOf("image") !== -1) {
  300. self.exec("insertimage", url);
  301. } else {
  302. html = '<a class="ke-insertfile" href="' + url + '" data-ke-src="' + url + '" target="_blank">' + (file.name || url) + '</a>';
  303. self.exec("inserthtml", html);
  304. }
  305. resolve();
  306. }, function () {
  307. resolve();
  308. });
  309. });
  310. } catch (e) {
  311. }
  312. }
  313. };
  314. getFileFromBase64 = function (data, url) {
  315. var arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1],
  316. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  317. while (n--) {
  318. u8arr[n] = bstr.charCodeAt(n);
  319. }
  320. var filename, suffix;
  321. if (typeof url != 'undefined') {
  322. var urlArr = url.split('.');
  323. filename = url.substr(url.lastIndexOf('/') + 1);
  324. suffix = urlArr.pop();
  325. } else {
  326. filename = Math.random().toString(36).substring(5, 15);
  327. }
  328. if (!suffix) {
  329. suffix = data.substring("data:image/".length, data.indexOf(";base64"));
  330. }
  331. var exp = new RegExp("\\." + suffix + "$", "i");
  332. filename = exp.test(filename) ? filename : filename + "." + suffix;
  333. var file = new File([u8arr], filename, {type: mime});
  334. return file;
  335. };
  336. $(Config.nkeditor.classname || '.editor', form).each(function () {
  337. var that = this;
  338. var options = $(this).data("nkeditor-options");
  339. var editor = Nkeditor.create(that, $.extend({}, {
  340. width: '100%',
  341. filterMode: false,
  342. wellFormatMode: false,
  343. allowMediaUpload: true, //是否允许媒体上传
  344. allowFileManager: true,
  345. allowImageUpload: true,
  346. baiduMapKey: Config.nkeditor.baidumapkey || '',
  347. baiduMapCenter: Config.nkeditor.baidumapcenter || '',
  348. fontSizeTable: ['9px', '10px', '12px', '14px', '16px', '18px', '21px', '24px', '32px'],
  349. formulaPreviewUrl: typeof Config.nkeditor != 'undefined' && Config.nkeditor.formulapreviewurl ? Config.nkeditor.formulapreviewurl : "", //数学公式的预览地址
  350. cssPath: Config.site.cdnurl + '/assets/addons/nkeditor/plugins/code/prism.css',
  351. cssData: "body {font-size: 13px}",
  352. fillDescAfterUploadImage: false, //是否在上传后继续添加描述信息
  353. themeType: typeof Config.nkeditor != 'undefined' ? Config.nkeditor.theme : 'black', //编辑器皮肤,这个值从后台获取
  354. fileManagerJson: Fast.api.fixurl("/addons/nkeditor/index/attachment/module/" + Config.modulename),
  355. items: [
  356. 'source', 'undo', 'redo', 'preview', 'print', 'template', 'code', 'quote', 'cut', 'copy', 'paste',
  357. 'plainpaste', 'justifyleft', 'justifycenter', 'justifyright',
  358. 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
  359. 'superscript', 'clearhtml', 'quickformat', 'selectall',
  360. 'formatblock', 'fontname', 'fontsize', 'forecolor', 'hilitecolor', 'bold',
  361. 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', 'image', 'multiimage', 'graft',
  362. 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
  363. 'anchor', 'link', 'unlink', 'remoteimage', 'search', 'math', 'about', 'fullscreen'
  364. ],
  365. afterCreate: function () {
  366. var self = this;
  367. //Ctrl+回车提交
  368. Nkeditor.ctrl(document, 13, function () {
  369. self.sync();
  370. $(that).closest("form").submit();
  371. });
  372. Nkeditor.ctrl(self.edit.doc, 13, function () {
  373. self.sync();
  374. $(that).closest("form").submit();
  375. });
  376. //粘贴上传
  377. $("body", self.edit.doc).bind('paste', function (event) {
  378. var originalEvent;
  379. originalEvent = event.originalEvent;
  380. if (originalEvent.clipboardData && originalEvent.clipboardData.files.length > 0) {
  381. uploadFiles.call(self, originalEvent.clipboardData.files);
  382. return false;
  383. }
  384. });
  385. //拖拽上传
  386. $("body", self.edit.doc).bind('drop', function (event) {
  387. var originalEvent;
  388. originalEvent = event.originalEvent;
  389. if (originalEvent.dataTransfer && originalEvent.dataTransfer.files.length > 0) {
  390. uploadFiles.call(self, originalEvent.dataTransfer.files);
  391. return false;
  392. }
  393. });
  394. },
  395. afterChange: function () {
  396. $(this.srcElement[0]).trigger("change");
  397. },
  398. //自定义处理
  399. beforeUpload: function (callback, file) {
  400. var file = file ? file : $("input.ke-upload-file", this.form).prop('files')[0];
  401. Upload.api.send(file, function (data) {
  402. var data = {code: '000', data: {url: Config.nkeditor.fullmode ? Fast.api.cdnurl(data.url, true) : Fast.api.cdnurl(data.url)}, title: '', width: '', height: '', border: '', align: ''};
  403. callback(data);
  404. });
  405. },
  406. //错误处理 handler
  407. errorMsgHandler: function (message, type) {
  408. try {
  409. Fast.api.msg(message);
  410. console.log(message, type);
  411. } catch (Error) {
  412. alert(message);
  413. }
  414. },
  415. uploadFiles: uploadFiles
  416. }, options || {}));
  417. $(this).data("nkeditor", editor);
  418. });
  419. });
  420. }
  421. }
  422. });
  423. require.config({
  424. paths: {
  425. 'previewfile': '../addons/previewfile/previewfile',
  426. },
  427. shim: {
  428. 'previewfile': {
  429. deps: ['bootstrap-table']
  430. },
  431. }
  432. });
  433. require.config({
  434. paths: {
  435. 'vue': '../addons/shop/js/vue.min',
  436. 'jquery-colorpicker': '../addons/shop/js/jquery.colorpicker.min',
  437. },
  438. shim: {
  439. 'jquery-colorpicker': {
  440. deps: ['jquery'],
  441. exports: '$.fn.extend'
  442. }
  443. }
  444. });
  445. if ($("table.table").size() > 0) {
  446. require(['previewfile', 'table'], function (Previewfile, Table) {
  447. });
  448. }
  449. if (Config.modulename === 'index' && Config.controllername === 'user' && ['login', 'register'].indexOf(Config.actionname) > -1 && $("#register-form,#login-form").length > 0 && $(".social-login").length == 0) {
  450. $("#register-form,#login-form").append(Config.third.loginhtml || '');
  451. }
  452. });