addons.js 18 KB

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