addons.js 18 KB

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