addons.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. define([], function () {
  2. require([], function () {
  3. //绑定data-toggle=addresspicker属性点击事件
  4. $(document).on('click', "[data-toggle='addresspicker']", function () {
  5. var that = this;
  6. var callback = $(that).data('callback');
  7. var input_id = $(that).data("input-id") ? $(that).data("input-id") : "";
  8. var lat_id = $(that).data("lat-id") ? $(that).data("lat-id") : "";
  9. var lng_id = $(that).data("lng-id") ? $(that).data("lng-id") : "";
  10. var lat = lat_id ? $("#" + lat_id).val() : '';
  11. var lng = lng_id ? $("#" + lng_id).val() : '';
  12. var url = "/addons/address/index/select";
  13. url += (lat && lng) ? '?lat=' + lat + '&lng=' + lng : '';
  14. Fast.api.open(url, '位置选择', {
  15. callback: function (res) {
  16. input_id && $("#" + input_id).val(res.address).trigger("change");
  17. lat_id && $("#" + lat_id).val(res.lat).trigger("change");
  18. lng_id && $("#" + lng_id).val(res.lng).trigger("change");
  19. try {
  20. //执行回调函数
  21. if (typeof callback === 'function') {
  22. callback.call(that, res);
  23. }
  24. } catch (e) {
  25. }
  26. }
  27. });
  28. });
  29. });
  30. if (typeof Config.upload.storage !== 'undefined' && Config.upload.storage === 'alioss') {
  31. require(['upload'], function (Upload) {
  32. //获取文件MD5值
  33. var getFileMd5 = function (file, cb) {
  34. require(['../addons/alioss/js/spark'], function (SparkMD5) {
  35. var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
  36. chunkSize = 10 * 1024 * 1024,
  37. chunks = Math.ceil(file.size / chunkSize),
  38. currentChunk = 0,
  39. spark = new SparkMD5.ArrayBuffer(),
  40. fileReader = new FileReader();
  41. fileReader.onload = function (e) {
  42. spark.append(e.target.result);
  43. currentChunk++;
  44. if (currentChunk < chunks) {
  45. loadNext();
  46. } else {
  47. cb && cb(spark.end());
  48. }
  49. };
  50. fileReader.onerror = function () {
  51. console.warn('文件读取错误');
  52. };
  53. function loadNext() {
  54. var start = currentChunk * chunkSize,
  55. end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
  56. fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  57. }
  58. loadNext();
  59. });
  60. };
  61. var _onInit = Upload.events.onInit;
  62. //初始化中完成判断
  63. Upload.events.onInit = function () {
  64. _onInit.apply(this, Array.prototype.slice.apply(arguments));
  65. //如果上传接口不是阿里OSS,则不处理
  66. if (this.options.url !== Config.upload.uploadurl) {
  67. return;
  68. }
  69. $.extend(this.options, {
  70. //关闭自动处理队列功能
  71. autoQueue: false,
  72. params: function (files, xhr, chunk) {
  73. var params = Config.upload.multipart;
  74. if (chunk) {
  75. return $.extend({}, params, {
  76. filesize: chunk.file.size,
  77. filename: chunk.file.name,
  78. chunkid: chunk.file.upload.uuid,
  79. chunkindex: chunk.index,
  80. chunkcount: chunk.file.upload.totalChunkCount,
  81. chunksize: this.options.chunkSize,
  82. chunkfilesize: chunk.dataBlock.data.size,
  83. width: chunk.file.width || 0,
  84. height: chunk.file.height || 0,
  85. type: chunk.file.type,
  86. uploadId: chunk.file.uploadId,
  87. key: chunk.file.key,
  88. });
  89. } else {
  90. params = $.extend({}, params, files[0].params);
  91. params.category = files[0].category || '';
  92. }
  93. return params;
  94. },
  95. chunkSuccess: function (chunk, file, response) {
  96. var etag = chunk.xhr.getResponseHeader("ETag").replace(/(^")|("$)/g, '');
  97. file.etags = file.etags ? file.etags : [];
  98. file.etags[chunk.index] = etag;
  99. },
  100. chunksUploaded: function (file, done) {
  101. var that = this;
  102. Fast.api.ajax({
  103. url: "/addons/alioss/index/upload",
  104. data: {
  105. action: 'merge',
  106. filesize: file.size,
  107. filename: file.name,
  108. chunkid: file.upload.uuid,
  109. chunkcount: file.upload.totalChunkCount,
  110. md5: file.md5,
  111. key: file.key,
  112. uploadId: file.uploadId,
  113. etags: file.etags,
  114. category: file.category || '',
  115. aliosstoken: Config.upload.multipart.aliosstoken,
  116. },
  117. }, function (data, ret) {
  118. done(JSON.stringify(ret));
  119. return false;
  120. }, function (data, ret) {
  121. file.accepted = false;
  122. that._errorProcessing([file], ret.msg);
  123. return false;
  124. });
  125. },
  126. });
  127. var _success = this.options.success;
  128. //先移除已有的事件
  129. this.off("success", _success).on("success", function (file, response) {
  130. var ret = {code: 0, msg: response};
  131. try {
  132. if (response) {
  133. ret = typeof response === 'string' ? JSON.parse(response) : response;
  134. }
  135. if (file.xhr.status === 200) {
  136. if (Config.upload.uploadmode === 'client') {
  137. ret = {code: 1, data: {url: '/' + file.key}};
  138. }
  139. if (ret.code == 1) {
  140. var url = ret.data.url || '';
  141. Fast.api.ajax({
  142. url: "/addons/alioss/index/notify",
  143. 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}
  144. }, function () {
  145. return false;
  146. }, function () {
  147. return false;
  148. });
  149. } else {
  150. console.error(ret);
  151. }
  152. } else {
  153. console.error(file.xhr);
  154. }
  155. } catch (e) {
  156. console.error(e);
  157. }
  158. _success.call(this, file, ret);
  159. });
  160. this.on("addedfile", function (file) {
  161. var that = this;
  162. setTimeout(function () {
  163. if (file.status === 'error') {
  164. return;
  165. }
  166. getFileMd5(file, function (md5) {
  167. var chunk = that.options.chunking && file.size > that.options.chunkSize ? 1 : 0;
  168. var params = $(that.element).data("params") || {};
  169. var category = typeof params.category !== 'undefined' ? params.category : ($(that.element).data("category") || '');
  170. category = typeof category === 'function' ? category.call(that, file) : category;
  171. Fast.api.ajax({
  172. url: "/addons/alioss/index/params",
  173. 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},
  174. }, function (data) {
  175. file.md5 = md5;
  176. file.id = data.id;
  177. file.key = data.key;
  178. file.date = data.date;
  179. file.uploadId = data.uploadId;
  180. file.policy = data.policy;
  181. file.signature = data.signature;
  182. file.partsAuthorization = data.partsAuthorization;
  183. file.params = data;
  184. file.category = category;
  185. if (file.status != 'error') {
  186. //开始上传
  187. that.enqueueFile(file);
  188. } else {
  189. that.removeFile(file);
  190. }
  191. return false;
  192. }, function () {
  193. that.removeFile(file);
  194. });
  195. });
  196. }, 0);
  197. });
  198. if (Config.upload.uploadmode === 'client') {
  199. var _method = this.options.method;
  200. var _url = this.options.url;
  201. this.options.method = function (files) {
  202. if (files[0].upload.chunked) {
  203. var chunk = null;
  204. files[0].upload.chunks.forEach(function (item) {
  205. if (item.status === 'uploading') {
  206. chunk = item;
  207. }
  208. });
  209. if (!chunk) {
  210. return "POST";
  211. } else {
  212. return "PUT";
  213. }
  214. }
  215. return _method;
  216. };
  217. this.options.url = function (files) {
  218. if (files[0].upload.chunked) {
  219. var chunk = null;
  220. files[0].upload.chunks.forEach(function (item) {
  221. if (item.status === 'uploading') {
  222. chunk = item;
  223. }
  224. });
  225. var index = chunk.dataBlock.chunkIndex;
  226. // debugger;
  227. this.options.headers = {"Authorization": "OSS " + files[0]['id'] + ":" + files[0]['partsAuthorization'][index], "x-oss-date": files[0]['date']};
  228. if (!chunk) {
  229. return Config.upload.uploadurl + "/" + files[0].key + "?uploadId=" + files[0].uploadId;
  230. } else {
  231. return Config.upload.uploadurl + "/" + files[0].key + "?partNumber=" + (index + 1) + "&uploadId=" + files[0].uploadId;
  232. }
  233. }
  234. return _url;
  235. };
  236. this.on("sending", function (file, xhr, formData) {
  237. var that = this;
  238. if (file.upload.chunked) {
  239. var _send = xhr.send;
  240. xhr.send = function () {
  241. var chunk = null;
  242. file.upload.chunks.forEach(function (item) {
  243. if (item.status == 'uploading') {
  244. chunk = item;
  245. }
  246. });
  247. if (chunk) {
  248. _send.call(xhr, chunk.dataBlock.data);
  249. }
  250. };
  251. }
  252. });
  253. }
  254. };
  255. });
  256. }
  257. window.UMEDITOR_HOME_URL = Config.__CDN__ + "/assets/addons/umeditor/";
  258. require.config({
  259. paths: {
  260. 'umeditor': '../addons/umeditor/umeditor.min',
  261. 'umeditor.config': '../addons/umeditor/umeditor.config',
  262. 'umeditor.lang': '../addons/umeditor/lang/zh-cn/zh-cn',
  263. },
  264. shim: {
  265. 'umeditor': {
  266. deps: [
  267. 'umeditor.config',
  268. 'css!../addons/umeditor/themes/default/css/umeditor.min.css'
  269. ],
  270. exports: 'UM',
  271. },
  272. 'umeditor.lang': ['umeditor']
  273. }
  274. });
  275. require(['form', 'upload'], function (Form, Upload) {
  276. var getFileFromBase64, uploadFiles;
  277. uploadFiles = async function (files, callback) {
  278. var self = this;
  279. for (var i = 0; i < files.length; i++) {
  280. try {
  281. await new Promise(function (resolve) {
  282. var url, html, file;
  283. file = files[i];
  284. Upload.api.send(file, function (data) {
  285. url = Fast.api.cdnurl(data.url, true);
  286. if (typeof callback === 'function') {
  287. callback.call(this, url, data)
  288. } else {
  289. if (file.type.indexOf("image") !== -1) {
  290. self.execCommand('insertImage', {
  291. src: url,
  292. title: file.name || "",
  293. });
  294. } else {
  295. self.execCommand('link', {
  296. href: url,
  297. title: file.name || "",
  298. target: '_blank'
  299. });
  300. }
  301. }
  302. resolve();
  303. }, function () {
  304. resolve();
  305. });
  306. });
  307. } catch (e) {
  308. }
  309. }
  310. };
  311. getFileFromBase64 = function (data, url) {
  312. var arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1],
  313. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  314. while (n--) {
  315. u8arr[n] = bstr.charCodeAt(n);
  316. }
  317. var filename, suffix;
  318. if (typeof url != 'undefined') {
  319. var urlArr = url.split('.');
  320. filename = url.substr(url.lastIndexOf('/') + 1);
  321. suffix = urlArr.pop();
  322. } else {
  323. filename = Math.random().toString(36).substring(5, 15);
  324. }
  325. if (!suffix) {
  326. suffix = data.substring("data:image/".length, data.indexOf(";base64"));
  327. }
  328. var exp = new RegExp("\\." + suffix + "$", "i");
  329. filename = exp.test(filename) ? filename : filename + "." + suffix;
  330. var file = new File([u8arr], filename, {type: mime});
  331. return file;
  332. };
  333. //监听上传文本框的事件
  334. $(document).on("edui.file.change", ".edui-image-file", function (e, up, me, input, callback) {
  335. uploadFiles.call(me.editor, this.files, function (url, data) {
  336. me.uploadComplete(JSON.stringify({url: url, state: "SUCCESS"}));
  337. });
  338. up.updateInput(input);
  339. me.toggleMask("上传中....");
  340. callback && callback();
  341. });
  342. var _bindevent = Form.events.bindevent;
  343. Form.events.bindevent = function (form) {
  344. _bindevent.apply(this, [form]);
  345. require(['umeditor', 'umeditor.lang'], function (UME, undefined) {
  346. //重写编辑器加载
  347. UME.plugins['autoupload'] = function () {
  348. var that = this;
  349. that.addListener('ready', function () {
  350. if (window.FormData && window.FileReader) {
  351. that.getOpt('pasteImageEnabled') && that.$body.on('paste', function (event) {
  352. var originalEvent;
  353. originalEvent = event.originalEvent;
  354. if (originalEvent.clipboardData && originalEvent.clipboardData.files.length > 0) {
  355. uploadFiles.call(that, originalEvent.clipboardData.files);
  356. return false;
  357. }
  358. });
  359. that.getOpt('dropFileEnabled') && that.$body.on('drop', function (event) {
  360. var originalEvent;
  361. originalEvent = event.originalEvent;
  362. if (originalEvent.dataTransfer && originalEvent.dataTransfer.files.length > 0) {
  363. uploadFiles.call(that, originalEvent.dataTransfer.files);
  364. return false;
  365. }
  366. });
  367. //取消拖放图片时出现的文字光标位置提示
  368. that.$body.on('dragover', function (e) {
  369. if (e.originalEvent.dataTransfer.types[0] == 'Files') {
  370. return false;
  371. }
  372. });
  373. }
  374. });
  375. };
  376. $.extend(window.UMEDITOR_CONFIG.whiteList, {
  377. div: ['style', 'class', 'id', 'data-tpl', 'data-source', 'data-id'],
  378. span: ['style', 'class', 'id', 'data-id']
  379. });
  380. $(Config.umeditor.classname || '.editor', form).each(function () {
  381. var id = $(this).attr("id");
  382. $(this).removeClass('form-control');
  383. var options = $(this).data("umeditor-options");
  384. UME.list[id] = UME.getEditor(id, $.extend(true, {}, {
  385. initialFrameWidth: '100%',
  386. zIndex: 90,
  387. autoHeightEnabled: true,
  388. initialFrameHeight: 300,
  389. xssFilterRules: false,
  390. outputXssFilter: false,
  391. inputXssFilter: false,
  392. autoFloatEnabled: false,
  393. pasteImageEnabled: true,
  394. dropFileEnabled: true,
  395. baiduMapKey: Config.umeditor.baidumapkey || '',
  396. baiduMapCenter: Config.umeditor.baidumapcenter || '',
  397. imageUrl: '',
  398. imagePath: '',
  399. imageUploadCallback: function (file, fn) {
  400. var me = this;
  401. Upload.api.send(file, function (data) {
  402. var url = data.url;
  403. fn && fn.call(me, url, data);
  404. });
  405. }
  406. }, options || {}));
  407. });
  408. });
  409. }
  410. });
  411. });