uploadFile.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. .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 id="btn" class="btn">
  16. <input v-if="compatibleFile" :multiple="multiple" @change="onChange" @click="onClick" :accept="accept" ref="file" class="file" type="file" />
  17. <div v-else @click="onClick" class="file"></div>
  18. </div>
  19. </div>
  20. <script type="text/javascript" src="js/vue.min.js"></script>
  21. <script type="text/javascript" src="js/permission.js"></script>
  22. <script type="text/javascript">
  23. let _this;
  24. var vm = new Vue({
  25. el: '#content',
  26. data: {
  27. accept: '',
  28. multiple: true,
  29. isIos: false,
  30. compatibleFile: false,
  31. dom: null
  32. },
  33. mounted() {
  34. this.debug&&console.log('加载webview');
  35. _this = this;
  36. this.files = new Map();
  37. document.addEventListener('plusready', (e)=>{
  38. let {debug,instantly,prohibited,parent,isVUE3} = plus.webview.currentWebview();
  39. this.isIos = (plus.os.name == "iOS");
  40. this.debug = debug;
  41. this.instantly = instantly;
  42. this.prohibited = prohibited;
  43. let module;
  44. if (isVUE3==='YES') {module = parent}
  45. else {module = parent.replace(/^\.\/(.*)\.\w+$/, '$1')}
  46. if (!module.includes(atob('bHNqLQ=='))) {return;}
  47. if (this.prohibited.multiple === 'false') {
  48. this.prohibited.multiple = false;
  49. }
  50. if (this.prohibited.isPermissionInToast === 'false') {
  51. this.prohibited.isPermissionInToast = false;
  52. }
  53. if (this.prohibited.isPermissionInModal === 'false') {
  54. this.prohibited.isPermissionInModal = false;
  55. }
  56. if (this.prohibited.toBase === 'false') {
  57. this.prohibited.toBase = false;
  58. }
  59. this.accept = prohibited.accept;
  60. this.multiple = this.prohibited.multiple;
  61. location.href = 'callback?retype=updateOption';
  62. if (!this.isIos && this.prohibited.permission.android.length) {
  63. try{
  64. this.dom = document.createElement('input');
  65. this.dom.type = 'file';
  66. this.dom.value = '';
  67. this.dom.accept = this.accept;
  68. this.dom.multiple = this.multiple;
  69. this.dom.onchange = event => {
  70. this.onChange(event)
  71. };
  72. }catch(e){
  73. console.error(e);
  74. this.compatibleFile = true;
  75. }
  76. }
  77. else {
  78. this.compatibleFile = true;
  79. }
  80. }, false);
  81. },
  82. methods: {
  83. toast(msg) {
  84. plus.nativeUI.toast(msg);
  85. },
  86. clear(name) {
  87. if (!name) {
  88. this.files.clear();
  89. return;
  90. }
  91. this.files.delete(name);
  92. },
  93. setData(option='{}') {
  94. this.debug&&console.log('更新参数:'+option);
  95. try{
  96. _this.option = JSON.parse(option);
  97. }catch(e){
  98. console.error('参数设置错误')
  99. }
  100. },
  101. async upload(name=''){
  102. if (name && this.files.has(name)) {
  103. await this.createUpload(this.files.get(name));
  104. }
  105. else {
  106. for (let item of this.files.values()) {
  107. if (item.type === 'waiting' || item.type === 'fail') {
  108. await this.createUpload(item);
  109. }
  110. }
  111. }
  112. },
  113. permissionModal(p) {
  114. let message = p.message || '是否前往开启权限?'
  115. plus.nativeUI.confirm(message,(e)=>{
  116. if (e.index === 0) {
  117. gotoAppPermissionSetting();
  118. }
  119. },'提示',['确定','取消']);
  120. },
  121. permissionToast(p) {
  122. if (this.prohibited.isPermissionInToast) {
  123. plus.nativeUI.toast(`<font style="font-size:14px">${p.message}</font>`,
  124. {
  125. type:'richtext',
  126. duration:'long',
  127. richTextStyle:{
  128. align:'center'
  129. },
  130. verticalAlign: 'top'
  131. });
  132. }
  133. else {
  134. location.href = `callback?retype=permissionBefore&permission=${p.value}&message=${encodeURIComponent(p.message)}`;
  135. }
  136. },
  137. async onClick(event) {
  138. if (this.isIos) {
  139. // ios未测过,因为现在没必要弹权限提示,android是因为华为bibi~,后面如果有问题可以联系我处理
  140. let permission = this.prohibited.permission.ios;
  141. if (permission && permission.length) {
  142. let t = null;
  143. for (let p of permission) {
  144. t = setTimeout(()=> {
  145. this.permissionToast(p);
  146. },500);
  147. let result = judgeIosPermission(p.value)
  148. if (!result) {
  149. this.debug&&console.error('用户未同意权限,提示用户申请');
  150. event.preventDefault();
  151. location.href = `callback?retype=permissionFail&permission=${p.value}&permissionResult=${result}&message=${encodeURIComponent(p.message)}`;
  152. if (this.prohibited.isPermissionInModal) {
  153. this.permissionModal(p);
  154. }
  155. }
  156. else {
  157. clearTimeout(t)
  158. }
  159. }
  160. }
  161. }
  162. else if (!this.compatibleFile) {
  163. let permission = this.prohibited.permission.android;
  164. if (permission && permission.length) {
  165. let t = null;
  166. for (let p of permission) {
  167. t = setTimeout(()=> {
  168. this.permissionToast(p);
  169. },200)
  170. let _dom = null;
  171. let result = await requestAndroidPermission(p.value)
  172. if (result !== 1) {
  173. event.preventDefault();
  174. this.debug&&console.error('用户未同意权限,提示用户申请');
  175. location.href = `callback?retype=permissionFail&permission=${p.value}&permissionResult=${result}&message=${encodeURIComponent(p.message)}`;
  176. if (this.prohibited.isPermissionInModal) {
  177. this.permissionModal(p);
  178. }
  179. return;
  180. }
  181. else {
  182. clearTimeout(t)
  183. }
  184. }
  185. clearTimeout(t)
  186. setTimeout(()=>{
  187. this.dom.click();
  188. this.dom.classList.add('file');
  189. document.getElementById('btn').appendChild(this.dom);
  190. },0)
  191. }
  192. else {
  193. setTimeout(()=>{
  194. this.dom.click();
  195. this.dom.classList.add('file');
  196. document.getElementById('btn').appendChild(this.dom);
  197. },0)
  198. }
  199. }
  200. },
  201. async onChange(e) {
  202. let fileDom;
  203. if (!this.compatibleFile) {
  204. fileDom = e.target || this.dom;
  205. }
  206. else {
  207. fileDom = this.$refs.file;
  208. }
  209. for (let file of fileDom.files) {
  210. if (this.files.size >= this.prohibited.count) {
  211. this.toast(`只允许上传${this.prohibited.count}个文件`);
  212. fileDom.value = '';
  213. break;
  214. }
  215. await this.addFile(file);
  216. }
  217. this.uploadAfter();
  218. fileDom.value = '';
  219. },
  220. addFile(file) {
  221. return new Promise((resolve,reject)=> {
  222. if (file) {
  223. let name = file.name;
  224. this.debug&&console.log('文件名称',name,'大小',file.size);
  225. // 限制文件格式
  226. let suffix = name.substring(name.lastIndexOf(".")+1).toLowerCase();
  227. let formats = this.prohibited.formats.toLowerCase();
  228. if (formats&&!formats.includes(suffix)) {
  229. this.toast(`不支持上传${suffix.toUpperCase()}格式文件`);
  230. return resolve();
  231. }
  232. // 限制文件大小
  233. if (file.size > 1024 * 1024 * Math.abs(this.prohibited.size)) {
  234. this.toast(`附件大小请勿超过${this.prohibited.size}M`)
  235. return resolve();
  236. }
  237. try{
  238. if (!this.prohibited.distinct) {
  239. let duplicateFile = [...this.files.keys()].filter(item=>{
  240. return (item.substring(0,item.lastIndexOf("("))||item.substring(0,item.lastIndexOf("."))) == name.substring(0,name.lastIndexOf(".")) &&
  241. item.substring(item.lastIndexOf(".")+1).toLowerCase() === suffix;
  242. })
  243. if (duplicateFile.length) {
  244. name = `${name.substring(0,name.lastIndexOf("."))}(${duplicateFile.length}).${suffix}`;
  245. }
  246. }
  247. }catch(e){
  248. name = Date.now() +'_'+ name;
  249. }
  250. let path = URL.createObjectURL(file);
  251. try{
  252. if (this.prohibited.toBase) {
  253. let reader = new FileReader();
  254. reader.readAsDataURL(file);
  255. let _this = this;
  256. reader.onload = function(){
  257. _this.files.set(name,{file:encodeURIComponent(this.result),path,name: name,size: file.size,progress: 0,type: 'waiting'});
  258. return resolve();
  259. }
  260. reader.onerror = function(){throw 'file to base64 error';}
  261. } else {
  262. throw '';
  263. }
  264. }catch(e){
  265. this.files.set(name,{file,path,name: name,size: file.size,progress: 0,type: 'waiting'});
  266. return resolve();
  267. }
  268. }
  269. })
  270. },
  271. /**
  272. * @returns {Map} 已选择的文件Map集
  273. */
  274. callChange() {
  275. location.href = 'callback?retype=change&files=' + encodeURIComponent(JSON.stringify([...this.files]));
  276. },
  277. /**
  278. * @returns {object} 正在处理的当前对象
  279. */
  280. changeFilesItem(item,end='') {
  281. this.files.set(item.name,item);
  282. location.href = 'callback?retype=progress&end='+ end +'&item=' + encodeURIComponent(JSON.stringify(item));
  283. },
  284. uploadAfter() {
  285. this.callChange();
  286. setTimeout(()=>{
  287. this.instantly&&this.upload();
  288. },1000)
  289. },
  290. createUpload(item) {
  291. this.debug&&console.log('准备上传,option=:'+JSON.stringify(this.option));
  292. item.type = 'loading';
  293. delete item.responseText;
  294. return new Promise((resolve,reject)=>{
  295. let {url,name,method='POST',header={},formData={}} = this.option;
  296. let form = new FormData();
  297. for (let keys in formData) {
  298. form.append(keys, formData[keys])
  299. }
  300. form.append(name, item.file);
  301. let xmlRequest = new XMLHttpRequest();
  302. xmlRequest.open(method, url, true);
  303. for (let keys in header) {
  304. xmlRequest.setRequestHeader(keys, header[keys])
  305. }
  306. xmlRequest.upload.addEventListener(
  307. 'progress',
  308. event => {
  309. if (event.lengthComputable) {
  310. let progress = Math.ceil((event.loaded * 100) / event.total)
  311. if (progress <= 100) {
  312. item.progress = progress;
  313. this.changeFilesItem(item);
  314. }
  315. }
  316. },
  317. false
  318. );
  319. xmlRequest.ontimeout = () => {
  320. console.error('请求超时')
  321. item.type = 'fail';
  322. this.changeFilesItem(item,true);
  323. return resolve(false);
  324. }
  325. xmlRequest.onreadystatechange = ev => {
  326. if (xmlRequest.readyState == 4) {
  327. this.debug && console.log('接口是否支持跨域',xmlRequest.withCredentials);
  328. if (xmlRequest.status == 200) {
  329. this.debug && console.log('上传完成:' + xmlRequest.responseText)
  330. item['responseText'] = xmlRequest.responseText;
  331. item.type = 'success';
  332. this.changeFilesItem(item,true);
  333. return resolve(true);
  334. } else if (xmlRequest.status == 0) {
  335. console.error('status = 0 :请检查请求头Content-Type与服务端是否匹配,服务端已正确开启跨域,并且nginx未拦截阻止请求')
  336. }
  337. console.error('--ERROR--:status = ' + xmlRequest.status)
  338. item.type = 'fail';
  339. this.changeFilesItem(item,true);
  340. return resolve(false);
  341. }
  342. }
  343. xmlRequest.send(form)
  344. });
  345. }
  346. }
  347. });
  348. </script>
  349. </body>
  350. </html>