fileupload.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. mbui.define(['layer'], function (exports) {
  2. function bytesToSize(bytes) {
  3. const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  4. if (bytes === 0) return '0 Bytes';
  5. const i = Math.floor(Math.log(bytes) / Math.log(1024));
  6. return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
  7. }
  8. function generateUniqueID(length) {
  9. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  10. let id = '';
  11. while (id.length < length) {
  12. id += chars.charAt(Math.floor(Math.random() * chars.length));
  13. }
  14. return id;
  15. }
  16. var layer = mbui.layer;
  17. var config = {
  18. uploadBtn: "uploadBtn",
  19. uploadBox: "uploadBox",
  20. url: "/api/index/upload",
  21. accept: "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf,.csv,image/*,text/plain,video/*,audio/*,application/x-zip-compressed",
  22. onlyImage: false,
  23. more:true,
  24. template:function(data){
  25. let exts = ['jpg', 'png', 'gif', 'jpeg'];
  26. let filesize = bytesToSize(data.filesize);
  27. let fileshow='<div class="mbui-file-icon" data-url="'+data.filepath+'" data-name="'+data.name+'"><i class="iconfont icon-weizhigeshi"></i></div>';
  28. if(exts.includes(data.fileext)){
  29. fileshow='<div class="mbui-file-icon file-img"><img src="'+data.filepath+'" alt="'+data.name+'"></div>';
  30. }
  31. return `<div class="mbui-file-div" data-id="${data.id}">
  32. ${fileshow}
  33. <div class="mbui-file-info">
  34. <div class="mbui-file-name line-limit-1">${data.name}</div>
  35. <div class="mbui-file-size">${filesize},刚刚</div>
  36. </div>
  37. <div class="mbui-file-del"><i class="iconfont icon-cuowukongxin"></i></div>
  38. </div>`;
  39. },
  40. ajaxUpload:null,
  41. loaded:0
  42. };
  43. // 初始化
  44. var fileUpload = function (options) {
  45. var timestamp = generateUniqueID(10);
  46. var settings = $.extend({}, config, options);
  47. //$.extend(true, that.config, options);
  48. if(settings.onlyImage){
  49. settings.accept = "image/jpeg,image/png,image/bmp";
  50. }
  51. var uploadBtn = $('#'+settings.uploadBtn),uploadBox = $('#'+settings.uploadBox),fileInput = 'fileInput_'+timestamp;
  52. uploadBox.append('<input id="'+fileInput+'" type="file" multiple="" accept="'+settings.accept+'" style="display:none;">');
  53. //点击上传
  54. uploadBtn.click(function() {
  55. let newtimestamp = Date.now();
  56. $('#'+fileInput).replaceWith($('<input type="file" id="'+fileInput+'" style="display:none;" multiple="" accept="'+settings.accept+'">'));
  57. if(settings.loaded == 0){
  58. $('#'+fileInput).click();
  59. }
  60. });
  61. //赋值到form表单
  62. function fileValue(){
  63. let file_array = [];
  64. uploadBox.find('.mbui-file-div').each(function () {
  65. let $id = $(this).data('id');
  66. file_array.push($id);
  67. });
  68. uploadBox.find('[data-type="file"]').val(file_array.join(','));
  69. }
  70. //删除已上传
  71. uploadBox.on('click','.mbui-file-del',function() {
  72. $(this).parent().remove();
  73. fileValue();
  74. });
  75. //附件上传
  76. uploadBox.on('change','#'+fileInput,function() {
  77. var fileInput = $(this)[0];
  78. var files = fileInput.files;
  79. console.log(files);
  80. //return false;
  81. if (files) {
  82. // 将文件列表转为数组
  83. const filesArray = Array.from(files);
  84. // 使用递归方式逐个上传到服务器
  85. function uploadNextFile(index) {
  86. if (index >= filesArray.length) {
  87. settings.loaded = 0;
  88. layer.closeAll();
  89. return;
  90. }
  91. const file = filesArray[index];
  92. const formData = new FormData();
  93. formData.append('file', file);
  94. $.ajax({
  95. url: settings.url,
  96. type: 'POST',
  97. data: formData,
  98. processData: false,
  99. contentType: false,
  100. beforeSend: function () {
  101. // 显示加载按钮
  102. settings.loaded = 1;
  103. layer.loading('文件上传中...');
  104. },
  105. complete:function(){
  106. uploadNextFile(index + 1); // 成功后上传下一个
  107. },
  108. success: function(res) {
  109. if(res.code==0){
  110. if(typeof(settings.ajaxUpload) == "undefined" || settings.ajaxUpload==null){
  111. var listItem = settings.template(res.data);
  112. console.log(index);
  113. if(settings.more==false){
  114. uploadBox.find('.mbui-file-div').remove();
  115. }
  116. uploadBox.append(listItem);
  117. }
  118. else{
  119. settings.ajaxUpload(res);
  120. }
  121. fileValue();
  122. }
  123. },
  124. error: function(xhr, status, error) {
  125. console.log('文件上传失败');
  126. console.log('错误信息:', error);
  127. }
  128. });
  129. }
  130. // 开始上传第一个文件
  131. uploadNextFile(0);
  132. } else {
  133. console.log('请选择要上传的文件');
  134. }
  135. });
  136. };
  137. function copyCtrl(content) {
  138. var save = function(e){
  139. e.clipboardData.setData('text/plain', content);
  140. e.preventDefault();
  141. }
  142. document.addEventListener('copy', save);
  143. document.execCommand('copy');
  144. document.removeEventListener('copy',save);
  145. if (content != '') {
  146. layer.msg('复制成功');
  147. }
  148. }
  149. function downloadFile(url, fileName) {
  150. let link = document.createElement("a");
  151. link.href = url;
  152. link.download = fileName;
  153. link.click();
  154. layer.loading('文件下载中...');
  155. }
  156. function isWeChat() {
  157. return /micromessenger/i.test(navigator.userAgent);
  158. }
  159. //查看图片
  160. $('body').on('click','.mbui-file-icon',function(e) {
  161. e.preventDefault();
  162. let img = $(this).find('img');
  163. let href = img.attr('src');
  164. if (href!=undefined && href!='') {
  165. layer.photo(href);
  166. }
  167. else {
  168. let url=window.location.origin + $(this).data('url');
  169. let name=$(this).data('name');
  170. if(isWeChat()){
  171. layer.open({
  172. type: 1,
  173. title: '温馨提示',
  174. content: '微信或企业微信不支持下载文件附件<br>请复制链接到手机浏览器下载查看',
  175. btn: ['复制链接'],
  176. yes:function(index){
  177. copyCtrl(url);
  178. layer.close(index);
  179. }
  180. });
  181. }
  182. else{
  183. downloadFile(url,name);
  184. }
  185. }
  186. });
  187. // 导出fileUpload模块
  188. exports('fileupload', function (options) {
  189. return new fileUpload(options);
  190. });
  191. });