uploadFile.html 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. <!DOCTYPE html>
  2. <html lang="zh-cn">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title class="title">[文件管理器]</title>
  6. <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
  7. <style type="text/css">
  8. .content {background: transparent;}
  9. .btn {position: relative;top: 0;left: 0;bottom: 0;right: 0;}
  10. .btn .file {position: fixed;z-index: 93;left: 0;right: 0;top: 0;bottom: 0;width: 100%;opacity: 0;}
  11. </style>
  12. </head>
  13. <body>
  14. <div id="content" class="content">
  15. <div class="btn">
  16. <input :multiple="multiple" @change="onChange" :accept="accept" ref="file" class="file" type="file" />
  17. </div>
  18. </div>
  19. <script type="text/javascript" src="js/vue.min.js"></script>
  20. <script type="text/javascript">
  21. let _this;
  22. var vm = new Vue({
  23. el: '#content',
  24. data: {
  25. accept: '',
  26. multiple: true,
  27. },
  28. mounted() {
  29. console.log('加载webview');
  30. _this = this;
  31. this.files = new Map();
  32. document.addEventListener('plusready', (e)=>{
  33. let {debug,instantly,prohibited} = plus.webview.currentWebview();
  34. this.debug = debug;
  35. this.instantly = instantly;
  36. this.prohibited = prohibited;
  37. this.accept = prohibited.accept;
  38. if (prohibited.multiple === 'false') {
  39. prohibited.multiple = false;
  40. }
  41. this.multiple = prohibited.multiple;
  42. location.href = 'callback?retype=updateOption';
  43. }, false);
  44. },
  45. methods: {
  46. toast(msg) {
  47. plus.nativeUI.toast(msg);
  48. },
  49. clear(name) {
  50. if (!name) {
  51. this.files.clear();
  52. return;
  53. }
  54. this.files.delete(name);
  55. },
  56. setData(option='{}') {
  57. this.debug&&console.log('更新参数:'+option);
  58. try{
  59. _this.option = JSON.parse(option);
  60. }catch(e){
  61. console.error('参数设置错误')
  62. }
  63. },
  64. async upload(name=''){
  65. if (name && this.files.has(name)) {
  66. await this.createUpload(this.files.get(name));
  67. }
  68. else {
  69. for (let item of this.files.values()) {
  70. if (item.type === 'waiting' || item.type === 'fail') {
  71. await this.createUpload(item);
  72. }
  73. }
  74. }
  75. },
  76. onChange(e) {
  77. let fileDom = this.$refs.file;
  78. for (let file of fileDom.files) {
  79. if (this.files.size >= this.prohibited.count) {
  80. this.toast(`只允许上传${this.prohibited.count}个文件`);
  81. fileDom.value = '';
  82. break;
  83. }
  84. this.addFile(file);
  85. }
  86. this.uploadAfter();
  87. fileDom.value = '';
  88. },
  89. addFile(file) {
  90. if (file) {
  91. let name = file.name;
  92. this.debug&&console.log('文件名称',name,'大小',file.size);
  93. // 限制文件格式
  94. let suffix = name.substring(name.lastIndexOf(".")+1).toLowerCase();
  95. let formats = this.prohibited.formats.toLowerCase();
  96. if (formats&&!formats.includes(suffix)) {
  97. this.toast(`不支持上传${suffix.toUpperCase()}格式文件`);
  98. return;
  99. }
  100. // 限制文件大小
  101. if (file.size > 1024 * 1024 * Math.abs(this.prohibited.size)) {
  102. this.toast(`附件大小请勿超过${this.prohibited.size}M`)
  103. return;
  104. }
  105. try{
  106. if (!this.prohibited.distinct) {
  107. let homonymIndex = [...this.files.keys()].findIndex(item=>{
  108. return (item.substring(0,item.lastIndexOf("("))||item.substring(0,item.lastIndexOf("."))) == name.substring(0,name.lastIndexOf(".")) &&
  109. item.substring(item.lastIndexOf(".")+1).toLowerCase() === suffix;
  110. })
  111. if (homonymIndex > -1) {
  112. name = `${name.substring(0,name.lastIndexOf("."))}(${homonymIndex+1}).${suffix}`;
  113. }
  114. }
  115. }catch(e){
  116. //TODO handle the exception
  117. }
  118. // let itemBlob = new Blob([file]);
  119. // let path = URL.createObjectURL(itemBlob);
  120. let path = URL.createObjectURL(file);
  121. this.files.set(name,{file,path,name: name,size: file.size,progress: 0,type: 'waiting'});
  122. }
  123. },
  124. /**
  125. * @returns {Map} 已选择的文件Map集
  126. */
  127. callChange() {
  128. location.href = 'callback?retype=change&files=' + escape(JSON.stringify([...this.files]));
  129. },
  130. /**
  131. * @returns {object} 正在处理的当前对象
  132. */
  133. changeFilesItem(item,end='') {
  134. this.files.set(item.name,item);
  135. location.href = 'callback?retype=progress&end='+ end +'&item=' + escape(JSON.stringify(item));
  136. },
  137. uploadAfter() {
  138. this.callChange();
  139. setTimeout(()=>{
  140. this.instantly&&this.upload();
  141. },1000)
  142. },
  143. createUpload(item) {
  144. this.debug&&console.log('准备上传,option=:'+JSON.stringify(this.option));
  145. item.type = 'loading';
  146. delete item.responseText;
  147. return new Promise((resolve,reject)=>{
  148. let {url,name,method='POST',header={},formData={}} = this.option;
  149. let form = new FormData();
  150. for (let keys in formData) {
  151. form.append(keys, formData[keys])
  152. }
  153. form.append(name, item.file);
  154. let xmlRequest = new XMLHttpRequest();
  155. xmlRequest.open(method, url, true);
  156. for (let keys in header) {
  157. xmlRequest.setRequestHeader(keys, header[keys])
  158. }
  159. xmlRequest.upload.addEventListener(
  160. 'progress',
  161. event => {
  162. if (event.lengthComputable) {
  163. let progress = Math.ceil((event.loaded * 100) / event.total)
  164. if (progress <= 100) {
  165. item.progress = progress;
  166. this.changeFilesItem(item);
  167. }
  168. }
  169. },
  170. false
  171. );
  172. xmlRequest.ontimeout = () => {
  173. console.error('请求超时')
  174. item.type = 'fail';
  175. this.changeFilesItem(item,true);
  176. return resolve(false);
  177. }
  178. xmlRequest.onreadystatechange = ev => {
  179. if (xmlRequest.readyState == 4) {
  180. this.debug && console.log('接口是否支持跨域',xmlRequest.withCredentials);
  181. if (xmlRequest.status == 200) {
  182. this.debug && console.log('上传完成:' + xmlRequest.responseText)
  183. item['responseText'] = xmlRequest.responseText;
  184. item.type = 'success';
  185. this.changeFilesItem(item,true);
  186. return resolve(true);
  187. } else if (xmlRequest.status == 0) {
  188. console.error('status = 0 :请检查请求头Content-Type与服务端是否匹配,服务端已正确开启跨域,并且nginx未拦截阻止请求')
  189. }
  190. console.error('--ERROR--:status = ' + xmlRequest.status)
  191. item.type = 'fail';
  192. this.changeFilesItem(item,true);
  193. return resolve(false);
  194. }
  195. }
  196. xmlRequest.send(form)
  197. });
  198. }
  199. }
  200. });
  201. </script>
  202. </body>
  203. </html>