require-upload.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. define(['jquery', 'bootstrap', 'dropzone', 'template'], function ($, undefined, Dropzone, Template) {
  2. var Upload = {
  3. list: {},
  4. options: {},
  5. config: {
  6. container: document.body,
  7. classname: '.plupload:not([initialized]),.faupload:not([initialized])',
  8. previewtpl: '<li class="col-xs-3"><a href="<%=fullurl%>" data-url="<%=url%>" target="_blank" class="thumbnail"><img src="<%=fullurl%>" onerror="this.src=\'' + Fast.api.fixurl("ajax/icon") + '?suffix=<%=suffix%>\';this.onerror=null;" class="img-responsive"></a><a href="javascript:;" class="btn btn-danger btn-xs btn-trash"><i class="fa fa-trash"></i></a></li>',
  9. },
  10. events: {
  11. //初始化
  12. onInit: function () {
  13. },
  14. //上传成功的回调
  15. onUploadSuccess: function (up, ret, file) {
  16. var button = up.element;
  17. var onUploadSuccess = up.options.onUploadSuccess;
  18. var data = typeof ret.data !== 'undefined' ? ret.data : null;
  19. //上传成功后回调
  20. if (button) {
  21. //如果有文本框则填充
  22. var input_id = $(button).data("input-id") ? $(button).data("input-id") : "";
  23. if (input_id) {
  24. var urlArr = [];
  25. var inputObj = $("#" + input_id);
  26. if ($(button).data("multiple") && inputObj.val() !== "") {
  27. urlArr.push(inputObj.val());
  28. }
  29. urlArr.push(data.url);
  30. inputObj.val(urlArr.join(",")).trigger("change").trigger("validate");
  31. }
  32. //如果有回调函数
  33. var onDomUploadSuccess = $(button).data("upload-success");
  34. if (onDomUploadSuccess) {
  35. if (typeof onDomUploadSuccess !== 'function' && typeof Upload.api.custom[onDomUploadSuccess] === 'function') {
  36. onDomUploadSuccess = Upload.api.custom[onDomUploadSuccess];
  37. }
  38. if (typeof onDomUploadSuccess === 'function') {
  39. var result = onDomUploadSuccess.call(button, data, ret);
  40. if (result === false)
  41. return;
  42. }
  43. }
  44. }
  45. if (typeof onUploadSuccess === 'function') {
  46. var result = onUploadSuccess.call(button, data, ret);
  47. if (result === false)
  48. return;
  49. }
  50. },
  51. //上传错误的回调
  52. onUploadError: function (up, ret, file) {
  53. var button = up.element;
  54. var onUploadError = up.options.onUploadError;
  55. var data = typeof ret.data !== 'undefined' ? ret.data : null;
  56. if (button) {
  57. var onDomUploadError = $(button).data("upload-error");
  58. if (onDomUploadError) {
  59. if (typeof onDomUploadError !== 'function' && typeof Upload.api.custom[onDomUploadError] === 'function') {
  60. onDomUploadError = Upload.api.custom[onDomUploadError];
  61. }
  62. if (typeof onDomUploadError === 'function') {
  63. var result = onDomUploadError.call(button, data, ret);
  64. if (result === false)
  65. return;
  66. }
  67. }
  68. }
  69. if (typeof onUploadError === 'function') {
  70. var result = onUploadError.call(button, data, ret);
  71. if (result === false) {
  72. return;
  73. }
  74. }
  75. Toastr.error(ret.msg.toString().replace(/(<([^>]+)>)/gi, "") + "(code:" + ret.code + ")");
  76. },
  77. //服务器响应数据后
  78. onUploadResponse: function (response, up, file) {
  79. try {
  80. var ret = typeof response === 'object' ? response : JSON.parse(response);
  81. if (!ret.hasOwnProperty('code')) {
  82. $.extend(ret, {code: -2, msg: response, data: null});
  83. }
  84. } catch (e) {
  85. var ret = {code: -1, msg: e.message, data: null};
  86. }
  87. return ret;
  88. },
  89. //上传全部结束后
  90. onUploadComplete: function (up, files) {
  91. var button = up.element;
  92. var onUploadComplete = up.options.onUploadComplete;
  93. if (button) {
  94. var onDomUploadComplete = $(button).data("upload-complete");
  95. if (onDomUploadComplete) {
  96. if (typeof onDomUploadComplete !== 'function' && typeof Upload.api.custom[onDomUploadComplete] === 'function') {
  97. onDomUploadComplete = Upload.api.custom[onDomUploadComplete];
  98. }
  99. if (typeof onDomUploadComplete === 'function') {
  100. var result = onDomUploadComplete.call(button, files);
  101. if (result === false)
  102. return;
  103. }
  104. }
  105. }
  106. if (typeof onUploadComplete === 'function') {
  107. var result = onUploadComplete.call(button, files);
  108. if (result === false) {
  109. return;
  110. }
  111. }
  112. }
  113. },
  114. api: {
  115. //上传接口
  116. upload: function (element, onUploadSuccess, onUploadError, onUploadComplete) {
  117. element = typeof element === 'undefined' ? Upload.config.classname : element;
  118. $(element, Upload.config.container).each(function () {
  119. if ($(this).attr("initialized")) {
  120. return true;
  121. }
  122. $(this).attr("initialized", true);
  123. var that = this;
  124. var id = $(this).prop("id") || $(this).prop("name") || Dropzone.uuidv4();
  125. var url = $(this).data("url");
  126. var maxsize = $(this).data("maxsize");
  127. var maxcount = $(this).data("maxcount");
  128. var mimetype = $(this).data("mimetype");
  129. var multipart = $(this).data("multipart");
  130. var multiple = $(this).data("multiple");
  131. //填充ID
  132. var input_id = $(that).data("input-id") ? $(that).data("input-id") : "";
  133. //预览ID
  134. var preview_id = $(that).data("preview-id") ? $(that).data("preview-id") : "";
  135. //上传URL
  136. url = url ? url : Config.upload.uploadurl;
  137. url = Fast.api.fixurl(url);
  138. var chunking = false, chunkSize = Config.upload.chunksize || 2097152;
  139. //最大可上传文件大小
  140. maxsize = typeof maxsize !== "undefined" ? maxsize : Config.upload.maxsize;
  141. //文件类型
  142. mimetype = typeof mimetype !== "undefined" ? mimetype : Config.upload.mimetype;
  143. //请求的表单参数
  144. multipart = typeof multipart !== "undefined" ? multipart : Config.upload.multipart;
  145. //是否支持批量上传
  146. multiple = typeof multiple !== "undefined" ? multiple : Config.upload.multiple;
  147. //后缀特殊处理
  148. mimetype = mimetype.split(",").map(function (k) {
  149. return k.indexOf("/") > -1 ? k : (!k || k === "*" || k.charAt(0) === "." ? k : "." + k);
  150. }).join(",");
  151. mimetype = mimetype === '*' ? null : mimetype;
  152. //最大文件限制转换成mb
  153. var maxFilesize = (function (maxsize) {
  154. var matches = maxsize.toString().match(/^([0-9\.]+)(\w+)$/);
  155. var size = matches ? parseFloat(matches[1]) : parseFloat(maxsize),
  156. unit = matches ? matches[2].toLowerCase() : 'b';
  157. var unitDict = {'b': 0, 'k': 1, 'kb': 1, 'm': 2, 'mb': 2, 'gb': 3, 'g': 3, 'tb': 4, 't': 4};
  158. var y = typeof unitDict[unit] !== 'undefined' ? unitDict[unit] : 0;
  159. var bytes = size * Math.pow(1024, y);
  160. return bytes / Math.pow(1024, 2);
  161. }(maxsize));
  162. var options = $(this).data() || {};
  163. delete options.success;
  164. delete options.url;
  165. multipart = $.isArray(multipart) ? {} : multipart;
  166. Upload.list[id] = new Dropzone(this, $.extend({
  167. url: url,
  168. params: function (files, xhr, chunk) {
  169. var params = multipart;
  170. if (chunk) {
  171. return $.extend({}, params, {
  172. filesize: chunk.file.size,
  173. filename: chunk.file.name,
  174. chunkid: chunk.file.upload.uuid,
  175. chunkindex: chunk.index,
  176. chunkcount: chunk.file.upload.totalChunkCount,
  177. chunksize: this.options.chunkSize,
  178. chunkfilesize: chunk.dataBlock.data.size,
  179. width: chunk.file.width || 0,
  180. height: chunk.file.height || 0,
  181. type: chunk.file.type,
  182. });
  183. }
  184. return params;
  185. },
  186. chunking: chunking,
  187. chunkSize: chunkSize,
  188. maxFilesize: maxFilesize,
  189. acceptedFiles: mimetype,
  190. maxFiles: (maxcount && parseInt(maxcount) > 1 ? maxcount : (multiple ? null : 1)),
  191. previewsContainer: false,
  192. dictDefaultMessage: __("Drop files here to upload"),
  193. dictFallbackMessage: __("Your browser does not support drag'n'drop file uploads"),
  194. dictFallbackText: __("Please use the fallback form below to upload your files like in the olden days"),
  195. dictFileTooBig: __("File is too big (%sMiB), Max filesize: %sMiB", "{{filesize}}", "{{maxFilesize}}"),
  196. dictInvalidFileType: __("You can't upload files of this type"),
  197. dictResponseError: __("Server responded with %s code.", "{{statusCode}}"),
  198. dictCancelUpload: __("Cancel upload"),
  199. dictUploadCanceled: __("Upload canceled"),
  200. dictCancelUploadConfirmation: __("Are you sure you want to cancel this upload?"),
  201. dictRemoveFile: __("Remove file"),
  202. dictMaxFilesExceeded: __("You can only upload a maximum of %s files", "{{maxFiles}}"),
  203. init: function () {
  204. Upload.events.onInit.call(this);
  205. //必须添加dz-message,否则点击icon无法唤起上传窗口
  206. $(">i", this.element).addClass("dz-message");
  207. this.options.elementHtml = $(this.element).html();
  208. },
  209. addedfiles: function (files) {
  210. if (this.options.maxFiles && (!this.options.maxFiles || this.options.maxFiles > 1) && this.options.inputId) {
  211. var inputObj = $("#" + this.options.inputId);
  212. if (inputObj.size() > 0) {
  213. var value = $.trim(inputObj.val());
  214. var nums = value === '' ? 0 : value.split(/\,/).length;
  215. var remain = this.options.maxFiles - nums;
  216. if (remain === 0 || files.length > remain) {
  217. files = Array.prototype.slice.call(files, remain);
  218. for (var i = 0; i < files.length; i++) {
  219. this.removeFile(files[i]);
  220. }
  221. Toastr.error(__("You can only upload a maximum of %s files", this.options.maxFiles));
  222. }
  223. }
  224. }
  225. },
  226. success: function (file, response) {
  227. var ret = Upload.events.onUploadResponse(response, this, file);
  228. file.ret = ret;
  229. if (ret.code === 1) {
  230. Upload.events.onUploadSuccess(this, ret, file);
  231. } else {
  232. Upload.events.onUploadError(this, ret, file);
  233. }
  234. },
  235. error: function (file, response, xhr) {
  236. var responseObj = $("<div>" + xhr.responseText + "</div>");
  237. responseObj.find("style, title, script").remove();
  238. var ret = {code: 0, data: null, msg: responseObj.text()};
  239. Upload.events.onUploadError(this, ret, file);
  240. },
  241. uploadprogress: function (file, progress, bytesSent) {
  242. },
  243. totaluploadprogress: function (progress, bytesSent) {
  244. if (this.getActiveFiles().length > 0) {
  245. $(this.element).prop("disabled", true).html("<i class='fa fa-upload'></i> " + __('Upload') + Math.floor(progress) + "%");
  246. }
  247. },
  248. queuecomplete: function () {
  249. Upload.events.onUploadComplete(this, this.files);
  250. this.removeAllFiles(true);
  251. $(this.element).prop("disabled", false).html(this.options.elementHtml);
  252. },
  253. chunkSuccess: function (chunk, file, response) {
  254. },
  255. chunksUploaded: function (file, done) {
  256. var that = this;
  257. Fast.api.ajax({
  258. url: this.options.url,
  259. data: {
  260. action: 'merge',
  261. filesize: file.size,
  262. filename: file.name,
  263. chunkid: file.upload.uuid,
  264. chunkcount: file.upload.totalChunkCount,
  265. }
  266. }, function (data, ret) {
  267. done(JSON.stringify(ret));
  268. return false;
  269. }, function (data, ret) {
  270. file.accepted = false;
  271. that._errorProcessing([file], ret.msg);
  272. });
  273. },
  274. onUploadSuccess: onUploadSuccess,
  275. onUploadError: onUploadError,
  276. onUploadComplete: onUploadComplete,
  277. }, Upload.options, options));
  278. //拖动排序
  279. if (preview_id && multiple) {
  280. require(['dragsort'], function () {
  281. $("#" + preview_id).dragsort({
  282. dragSelector: "li a:not(.btn-trash)",
  283. dragEnd: function () {
  284. $("#" + preview_id).trigger("fa.preview.change");
  285. },
  286. placeHolderTemplate: '<li class="col-xs-3"></li>'
  287. });
  288. });
  289. }
  290. //刷新隐藏textarea的值
  291. var refresh = function (name) {
  292. var data = {};
  293. var textarea = $("textarea[name='" + name + "']");
  294. var container = textarea.prev("ul");
  295. $.each($("input,select,textarea", container).serializeArray(), function (i, j) {
  296. var reg = /\[?(\w+)\]?\[(\w+)\]$/g;
  297. var match = reg.exec(j.name);
  298. if (!match)
  299. return true;
  300. if (!isNaN(match[2])) {
  301. data[i] = j.value;
  302. } else {
  303. match[1] = "x" + parseInt(match[1]);
  304. if (typeof data[match[1]] === 'undefined') {
  305. data[match[1]] = {};
  306. }
  307. data[match[1]][match[2]] = j.value;
  308. }
  309. });
  310. var result = [];
  311. $.each(data, function (i, j) {
  312. result.push(j);
  313. });
  314. textarea.val(JSON.stringify(result));
  315. };
  316. if (preview_id && input_id) {
  317. $(document.body).on("keyup change", "#" + input_id, function (e) {
  318. var inputStr = $("#" + input_id).val();
  319. var inputArr = inputStr.split(/\,/);
  320. $("#" + preview_id).empty();
  321. var tpl = $("#" + preview_id).data("template") ? $("#" + preview_id).data("template") : "";
  322. var extend = $("#" + preview_id).next().is("textarea") ? $("#" + preview_id).next("textarea").val() : "{}";
  323. var json = {};
  324. try {
  325. json = JSON.parse(extend);
  326. } catch (e) {
  327. }
  328. $.each(inputArr, function (i, j) {
  329. if (!j) {
  330. return true;
  331. }
  332. var suffix = /[\.]?([a-zA-Z0-9]+)$/.exec(j);
  333. suffix = suffix ? suffix[1] : 'file';
  334. var data = {url: j, fullurl: Fast.api.cdnurl(j), data: $(that).data(), key: i, index: i, value: (json && typeof json[i] !== 'undefined' ? json[i] : null), suffix: suffix};
  335. var html = tpl ? Template(tpl, data) : Template.render(Upload.config.previewtpl, data);
  336. $("#" + preview_id).append(html);
  337. });
  338. });
  339. $("#" + input_id).trigger("change");
  340. }
  341. if (preview_id) {
  342. //监听文本框改变事件
  343. $("#" + preview_id).on('change keyup', "input,textarea,select", function () {
  344. refresh($(this).closest("ul").data("name"));
  345. });
  346. // 监听事件
  347. $(document.body).on("fa.preview.change", "#" + preview_id, function () {
  348. var urlArr = [];
  349. $("#" + preview_id + " [data-url]").each(function (i, j) {
  350. urlArr.push($(this).data("url"));
  351. });
  352. if (input_id) {
  353. $("#" + input_id).val(urlArr.join(","));
  354. }
  355. refresh($("#" + preview_id).data("name"));
  356. });
  357. // 移除按钮事件
  358. $(document.body).on("click", "#" + preview_id + " .btn-trash", function () {
  359. $(this).closest("li").remove();
  360. $("#" + preview_id).trigger("fa.preview.change");
  361. });
  362. }
  363. if (input_id) {
  364. //粘贴上传、拖拽上传
  365. $("body").on('paste drop', "#" + input_id, function (event) {
  366. var originEvent = event.originalEvent;
  367. var button = $(".plupload[data-input-id='" + $(this).attr("id") + "'],.faupload[data-input-id='" + $(this).attr("id") + "']");
  368. if (event.type === 'paste' && originEvent.clipboardData && originEvent.clipboardData.items) {
  369. var items = originEvent.clipboardData.items;
  370. if ((items.length === 1 && items[0].type.indexOf("text") > -1) || (items.length === 2 && items[1].type.indexOf("text") > -1)) {
  371. } else {
  372. Upload.list[button.attr("id")].paste(originEvent);
  373. return false;
  374. }
  375. }
  376. if (event.type === 'drop' && originEvent.dataTransfer && originEvent.dataTransfer.files) {
  377. Upload.list[button.attr("id")].drop(originEvent);
  378. return false;
  379. }
  380. });
  381. }
  382. });
  383. },
  384. /**
  385. * @deprecated Use upload instead.
  386. */
  387. plupload: function (element, onUploadSuccess, onUploadError, onUploadComplete) {
  388. return Upload.api.upload(element, onUploadSuccess, onUploadError, onUploadComplete);
  389. },
  390. /**
  391. * @deprecated Use upload instead.
  392. */
  393. faupload: function (element, onUploadSuccess, onUploadError, onUploadComplete) {
  394. return Upload.api.upload(element, onUploadSuccess, onUploadError, onUploadComplete);
  395. },
  396. // AJAX异步上传
  397. send: function (file, onUploadSuccess, onUploadError, onUploadComplete) {
  398. var index = Layer.msg(__('Uploading'), {offset: 't', time: 0});
  399. var id = "dropzone-" + Dropzone.uuidv4();
  400. $('<button type="button" id="' + id + '" class="btn btn-danger hidden faupload" />').appendTo("body");
  401. $("#" + id).data("upload-complete", function (files) {
  402. Layer.close(index);
  403. Upload.list[id].removeAllFiles(true);
  404. });
  405. Upload.api.upload("#" + id, onUploadSuccess, onUploadError, onUploadComplete);
  406. setTimeout(function () {
  407. Upload.list[id].addFile(file);
  408. }, 1);
  409. },
  410. custom: {
  411. //自定义上传完成回调
  412. afteruploadcallback: function (response) {
  413. console.log(this, response);
  414. alert("Custom Callback,Response URL:" + response.url);
  415. },
  416. }
  417. }
  418. }
  419. ;
  420. return Upload;
  421. });