addons.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. var _onInit = Upload.events.onInit;
  34. //初始化中完成判断
  35. Upload.events.onInit = function () {
  36. _onInit.apply(this, Array.prototype.slice.apply(arguments));
  37. //如果上传接口不是COS,则不处理
  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. chunkfilesize: chunk.dataBlock.data.size,
  54. chunksize: this.options.chunkSize,
  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. this.etags = this.etags ? this.etags : [];
  70. this.etags[chunk.index] = etag;
  71. },
  72. chunksUploaded: function (file, done) {
  73. var that = this;
  74. Fast.api.ajax({
  75. url: "/addons/cos/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: this.etags,
  86. category: file.category || '',
  87. costoken: Config.upload.multipart.costoken,
  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 || file.xhr.status === 204) {
  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/cos/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 || '', costoken: Config.upload.multipart.costoken}
  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/cos/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, costoken: Config.upload.multipart.costoken},
  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": files[0]['partsAuthorization'][index], "x-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.options.params = function (files, xhr, chunk) {
  209. var params = Config.upload.multipart;
  210. if (chunk) {
  211. return $.extend({}, params, {
  212. filesize: chunk.file.size,
  213. filename: chunk.file.name,
  214. chunkid: chunk.file.upload.uuid,
  215. chunkindex: chunk.index,
  216. chunkcount: chunk.file.upload.totalChunkCount,
  217. chunkfilesize: chunk.dataBlock.data.size,
  218. width: chunk.file.width || 0,
  219. height: chunk.file.height || 0,
  220. type: chunk.file.type,
  221. });
  222. } else {
  223. var retParams = $.extend({}, params, files[0].params || {});
  224. delete retParams.costoken;
  225. return retParams;
  226. }
  227. };
  228. this.on("sending", function (file, xhr, formData) {
  229. var that = this;
  230. if (file.upload.chunked) {
  231. var _send = xhr.send;
  232. xhr.send = function () {
  233. var chunk = null;
  234. file.upload.chunks.forEach(function (item) {
  235. if (item.status == 'uploading') {
  236. chunk = item;
  237. }
  238. });
  239. if (chunk) {
  240. _send.call(xhr, chunk.dataBlock.data);
  241. }
  242. };
  243. } else {
  244. }
  245. });
  246. }
  247. };
  248. });
  249. }
  250. require.config({
  251. paths: {
  252. 'async': '../addons/example/js/async',
  253. 'BMap': ['//api.map.baidu.com/api?v=2.0&ak=mXijumfojHnAaN2VxpBGoqHM'],
  254. },
  255. shim: {
  256. 'BMap': {
  257. deps: ['jquery'],
  258. exports: 'BMap'
  259. }
  260. }
  261. });
  262. require.config({
  263. paths: {
  264. 'designer': '../addons/poster/js/designer',
  265. 'jquery.contextMenu': '../addons/poster/js/jquery.contextMenu',
  266. 'jquery-colorpicker': '../addons/poster/js/jquery.colorpicker.min',
  267. }
  268. });
  269. window.UMEDITOR_HOME_URL = Config.__CDN__ + "/assets/addons/umeditor/";
  270. require.config({
  271. paths: {
  272. 'umeditor': '../addons/umeditor/umeditor.min',
  273. 'umeditor.config': '../addons/umeditor/umeditor.config',
  274. 'umeditor.lang': '../addons/umeditor/lang/zh-cn/zh-cn',
  275. },
  276. shim: {
  277. 'umeditor': {
  278. deps: [
  279. 'umeditor.config',
  280. 'css!../addons/umeditor/themes/default/css/umeditor.min.css'
  281. ],
  282. exports: 'UM',
  283. },
  284. 'umeditor.lang': ['umeditor']
  285. }
  286. });
  287. require(['form', 'upload'], function (Form, Upload) {
  288. //监听上传文本框的事件
  289. $(document).on("edui.file.change", ".edui-image-file", function (e, up, me, input, callback) {
  290. for (var i = 0; i < this.files.length; i++) {
  291. Upload.api.send(this.files[i], function (data) {
  292. var url = data.url;
  293. me.uploadComplete(JSON.stringify({url: url, state: "SUCCESS"}));
  294. });
  295. }
  296. up.updateInput(input);
  297. me.toggleMask("Loading....");
  298. callback && callback();
  299. });
  300. var _bindevent = Form.events.bindevent;
  301. Form.events.bindevent = function (form) {
  302. _bindevent.apply(this, [form]);
  303. require(['umeditor', 'umeditor.lang'], function (UME, undefined) {
  304. //重写编辑器加载
  305. UME.plugins['autoupload'] = function () {
  306. var me = this;
  307. me.setOpt('pasteImageEnabled', true);
  308. me.setOpt('dropFileEnabled', true);
  309. var sendAndInsertImage = function (file, editor) {
  310. try {
  311. Upload.api.send(file, function (data) {
  312. var url = Fast.api.cdnurl(data.url, true);
  313. editor.execCommand('insertimage', {
  314. src: url,
  315. _src: url
  316. });
  317. });
  318. } catch (er) {
  319. }
  320. };
  321. function getPasteImage(e) {
  322. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items : null;
  323. }
  324. function getDropImage(e) {
  325. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files : null;
  326. }
  327. me.addListener('ready', function () {
  328. if (window.FormData && window.FileReader) {
  329. var autoUploadHandler = function (e) {
  330. var hasImg = false,
  331. items;
  332. //获取粘贴板文件列表或者拖放文件列表
  333. items = e.type == 'paste' ? getPasteImage(e.originalEvent) : getDropImage(e.originalEvent);
  334. if (items) {
  335. var len = items.length,
  336. file;
  337. while (len--) {
  338. file = items[len];
  339. if (file.getAsFile)
  340. file = file.getAsFile();
  341. if (file && file.size > 0 && /image\/\w+/i.test(file.type)) {
  342. sendAndInsertImage(file, me);
  343. hasImg = true;
  344. }
  345. }
  346. if (hasImg)
  347. return false;
  348. }
  349. };
  350. me.getOpt('pasteImageEnabled') && me.$body.on('paste', autoUploadHandler);
  351. me.getOpt('dropFileEnabled') && me.$body.on('drop', autoUploadHandler);
  352. //取消拖放图片时出现的文字光标位置提示
  353. me.$body.on('dragover', function (e) {
  354. if (e.originalEvent.dataTransfer.types[0] == 'Files') {
  355. return false;
  356. }
  357. });
  358. }
  359. });
  360. };
  361. $.extend(window.UMEDITOR_CONFIG.whiteList, {
  362. div: ['style', 'class', 'id', 'data-tpl', 'data-source', 'data-id'],
  363. span: ['style', 'class', 'id', 'data-id']
  364. });
  365. $(Config.umeditor.classname || '.editor', form).each(function () {
  366. var id = $(this).attr("id");
  367. $(this).removeClass('form-control');
  368. var options = $(this).data("umeditor-options");
  369. UME.list[id] = UME.getEditor(id, $.extend(true, {}, {
  370. initialFrameWidth: '100%',
  371. zIndex: 90,
  372. autoHeightEnabled: true,
  373. initialFrameHeight: 300,
  374. xssFilterRules: false,
  375. outputXssFilter: false,
  376. inputXssFilter: false,
  377. autoFloatEnabled: false,
  378. imageUrl: '',
  379. imagePath: Config.upload.cdnurl,
  380. imageUploadCallback: function (file, fn) {
  381. var me = this;
  382. Upload.api.send(file, function (data) {
  383. var url = data.url;
  384. fn && fn.call(me, url, data);
  385. });
  386. }
  387. }, options || {}));
  388. });
  389. });
  390. }
  391. });
  392. });