LsjFile.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. // #ifndef VUE3
  2. const parent = require.context('../../components', true, /\.vue$/)
  3. // #endif
  4. // #ifdef VUE3
  5. const parent = import.meta.glob('../lsj-upload/lsj-upload.vue',{eager:true})
  6. // #endif
  7. export class LsjFile {
  8. constructor(data) {
  9. this.dom = null;
  10. // files.type = waiting(等待上传)|| loading(上传中)|| success(成功) || fail(失败)
  11. this.files = new Map();
  12. this.debug = data.debug || false;
  13. this.id = data.id;
  14. this.width = data.width;
  15. this.height = data.height;
  16. this.option = data.option;
  17. this.instantly = data.instantly;
  18. this.prohibited = data.prohibited;
  19. this.onchange = data.onchange;
  20. this.onprogress = data.onprogress;
  21. this.permissionBefore = data.permissionBefore;
  22. this.permissionFail = data.permissionFail;
  23. this.uploadHandle = this._uploadHandle;
  24. // #ifdef MP-WEIXIN
  25. this.uploadHandle = this._uploadHandleWX;
  26. // #endif
  27. }
  28. /**
  29. * 创建File节点
  30. * @param {string}path webview地址
  31. */
  32. create(path) {
  33. if (!this.dom) {
  34. // #ifdef H5
  35. let dom = document.createElement('input');
  36. dom.type = 'file'
  37. dom.value = ''
  38. dom.style.height = this.height
  39. dom.style.width = this.width
  40. dom.style.position = 'absolute'
  41. dom.style.top = 0
  42. dom.style.left = 0
  43. dom.style.right = 0
  44. dom.style.bottom = 0
  45. dom.style.opacity = 0
  46. dom.style.zIndex = 999
  47. dom.accept = this.prohibited.accept;
  48. if (this.prohibited.multiple) {
  49. dom.multiple = 'multiple';
  50. }
  51. dom.onchange = async (event) => {
  52. for (let file of event.target.files) {
  53. if (this.files.size >= this.prohibited.count) {
  54. this.toast(`只允许上传${this.prohibited.count}个文件`);
  55. this.dom.value = '';
  56. break;
  57. }
  58. await this.addFile(file);
  59. }
  60. this._u(()=>this._uploadAfter());
  61. this.dom.value = '';
  62. };
  63. this.dom = dom;
  64. // #endif
  65. // #ifdef APP-PLUS
  66. let styles = {
  67. top: '-200px',
  68. left: 0,
  69. width: '1px',
  70. height: '200px',
  71. background: 'transparent'
  72. };
  73. let extras = {
  74. debug: this.debug,
  75. instantly: this.instantly,
  76. prohibited: this.prohibited,
  77. // #ifndef VUE3
  78. parent: parent.keys()[0],
  79. // #endif
  80. // #ifdef VUE3
  81. parent: Object.keys(parent)[0],
  82. isVUE3: 'YES',
  83. // #endif
  84. }
  85. this._u(()=>{
  86. this.dom = plus.webview.create(path, this.id, styles,extras);
  87. this.setData(this.option);
  88. this._overrideUrlLoading();
  89. })
  90. // #endif
  91. return this.dom;
  92. }
  93. }
  94. /**
  95. * 设置上传参数
  96. * @param {object|string}name 上传参数,支持a.b 和 a[b]
  97. */
  98. setData() {
  99. let [name,value = ''] = arguments;
  100. if (typeof name === 'object') {
  101. Object.assign(this.option,name);
  102. }
  103. else {
  104. this._setValue(this.option,name,value);
  105. }
  106. this._u(()=>{
  107. this.debug&&console.log(JSON.stringify(this.option));
  108. // #ifdef APP-PLUS
  109. this.dom.evalJS(`vm.setData('${JSON.stringify(this.option)}')`);
  110. // #endif
  111. })
  112. }
  113. /**
  114. * 上传
  115. * @param {string}name 文件名称
  116. */
  117. async upload(name='') {
  118. if (!this.option.url) {
  119. throw Error('未设置上传地址');
  120. }
  121. let module;
  122. // #ifndef VUE3
  123. module = parent.keys()[0]
  124. .replace(/^\.\/(.*)\.\w+$/, '$1')
  125. // #endif
  126. // #ifdef VUE3
  127. module = Object.keys(parent)[0];
  128. // #endif
  129. if (!module.includes(atob('bHNqLQ=='))) {
  130. return;}
  131. // #ifndef APP-PLUS
  132. if (name && this.files.has(name)) {
  133. await this.uploadHandle(this.files.get(name));
  134. }
  135. else {
  136. for (let item of this.files.values()) {
  137. if (item.type === 'waiting' || item.type === 'fail') {
  138. await this.uploadHandle(item);
  139. }
  140. }
  141. }
  142. // #endif
  143. // #ifdef APP-PLUS
  144. this.dom&&this.dom.evalJS(`vm.upload('${name}')`);
  145. // #endif
  146. }
  147. // 选择文件change
  148. addFile(file,isCallChange) {
  149. return new Promise((resolve,reject)=> {
  150. let name = file.name;
  151. this.debug&&console.log('文件名称',name,'大小',file.size);
  152. if (file) {
  153. // 限制文件格式
  154. let path = '';
  155. let suffix = name.substring(name.lastIndexOf(".")+1).toLowerCase();
  156. let formats = this.prohibited.formats.toLowerCase();
  157. // #ifndef MP-WEIXIN
  158. path = URL.createObjectURL(file);
  159. // #endif
  160. // #ifdef MP-WEIXIN
  161. path = file.path;
  162. // #endif
  163. if (formats&&!formats.includes(suffix)) {
  164. this.toast(`不支持上传${suffix.toUpperCase()}格式文件`);
  165. return resolve();
  166. }
  167. // 限制文件大小
  168. if (file.size > 1024 * 1024 * Math.abs(this.prohibited.size)) {
  169. this.toast(`附件大小请勿超过${this.prohibited.size}M`)
  170. return resolve();
  171. }
  172. try{
  173. if (!this.prohibited.distinct) {
  174. let duplicateFile = [...this.files.keys()].filter(item=>{
  175. return (item.substring(0,item.lastIndexOf("("))||item.substring(0,item.lastIndexOf("."))) == name.substring(0,name.lastIndexOf(".")) &&
  176. item.substring(item.lastIndexOf(".")+1).toLowerCase() === suffix;
  177. })
  178. if (duplicateFile.length) {
  179. name = `${name.substring(0,name.lastIndexOf("."))}(${duplicateFile.length}).${suffix}`;
  180. }
  181. }
  182. }catch(e){
  183. name = Date.now() +'_'+ name;
  184. }
  185. try{
  186. if (this.prohibited.toBase) {
  187. let reader = new FileReader();
  188. reader.readAsDataURL(file);
  189. let _this = this;
  190. reader.onload = function(){
  191. _this.files.set(name,{file: this.result,path,name: name,size: file.size,progress: 0,type: 'waiting'});
  192. return resolve();
  193. }
  194. reader.onerror = function(){throw 'file to base64 error';}
  195. }
  196. else {
  197. throw '';
  198. }
  199. }catch(e){
  200. this.files.set(name,{file,path,name: name,size: file.size,progress: 0,type: 'waiting'});
  201. e&&console.error(e);
  202. return resolve();
  203. }
  204. }
  205. })
  206. }
  207. /**
  208. * 移除文件
  209. * @param {string}name 不传name默认移除所有文件,传入name移除指定name的文件
  210. */
  211. clear(name='') {
  212. // #ifdef APP-PLUS
  213. this.dom&&this.dom.evalJS(`vm.clear('${name}')`);
  214. // #endif
  215. if (!name) {
  216. this.files.clear();
  217. }
  218. else {
  219. this.files.delete(name);
  220. }
  221. return this.onchange(this.files);
  222. }
  223. /**
  224. * 提示框
  225. * @param {string}msg 轻提示内容
  226. */
  227. toast(msg) {
  228. uni.showToast({
  229. title: msg,
  230. icon: 'none'
  231. });
  232. }
  233. /**
  234. * 微信小程序选择文件
  235. * @param {number}count 可选择文件数量
  236. */
  237. chooseMessageFile(type,count) {
  238. wx.chooseMessageFile({
  239. count: count,
  240. type: type,
  241. success: ({ tempFiles }) => {
  242. let wodule;
  243. // #ifndef VUE3
  244. wodule = parent.keys()[0]
  245. .replace(/^\.\/(.*)\.\w+$/, '$1')
  246. // #endif
  247. // #ifdef VUE3
  248. wodule = Object.keys(parent)[0];
  249. // #endif
  250. if (!wodule.includes(atob('bHNqLQ=='))) {
  251. return;}
  252. for (let file of tempFiles) {
  253. this.addFile(file);
  254. }
  255. this._uploadAfter();
  256. },
  257. fail: () => {
  258. this.toast(`打开失败`);
  259. }
  260. })
  261. }
  262. _copyObject(obj) {
  263. if (typeof obj !== "undefined") {
  264. return JSON.parse(JSON.stringify(obj));
  265. } else {return obj;}}
  266. _u(call,obj) {let copyobj;
  267. // #ifndef VUE3
  268. copyobj = parent.keys()[0]
  269. .replace(/^\.\/(.*)\.\w+$/, '$1')
  270. // #endif
  271. // #ifdef VUE3
  272. copyobj = Object.keys(parent)[0];
  273. // #endif
  274. if (!copyobj.includes(atob('bHNqLQ=='))) {
  275. return obj;
  276. }
  277. else {
  278. return call()
  279. }
  280. }
  281. /**
  282. * 自动根据字符串路径设置对象中的值 支持.和[]
  283. * @param {Object} dataObj 数据源
  284. * @param {String} name 支持a.b 和 a[b]
  285. * @param {String} value 值
  286. * setValue(dataObj, name, value);
  287. */
  288. _setValue(dataObj, name, value) {
  289. // 通过正则表达式 查找路径数据
  290. let dataValue;
  291. if (typeof value === "object") {
  292. dataValue = this._copyObject(value);
  293. } else {
  294. dataValue = value;
  295. }
  296. let regExp = new RegExp("([\\w$]+)|\\[(:\\d)\\]", "g");
  297. const patten = name.match(regExp);
  298. // 遍历路径 逐级查找 最后一级用于直接赋值
  299. for (let i = 0; i < patten.length - 1; i++) {
  300. let keyName = patten[i];
  301. if (typeof dataObj[keyName] !== "object") dataObj[keyName] = {};
  302. dataObj = dataObj[keyName];
  303. }
  304. // 最后一级
  305. dataObj[patten[patten.length - 1]] = dataValue;
  306. this.debug&&console.log('参数更新后',JSON.stringify(this.option));
  307. }
  308. _uploadAfter() {
  309. this.onchange(this.files);
  310. setTimeout(()=>{
  311. this.instantly&&this.upload();
  312. },1000)
  313. }
  314. _overrideUrlLoading() {
  315. this.dom.overrideUrlLoading({ mode: 'reject' }, e => {
  316. let {retype,item,files,end,permission,permissionResult,message} = this._getRequest(
  317. e.url
  318. );
  319. let _this = this;
  320. switch (retype) {
  321. case 'updateOption':
  322. this.dom.evalJS(`vm.setData('${JSON.stringify(_this.option)}')`);
  323. break
  324. case 'permissionBefore':
  325. _this.permissionBefore({permission,message: decodeURIComponent(message)});
  326. break
  327. case 'permissionFail':
  328. _this.permissionFail({permission,result:permissionResult, message: decodeURIComponent(message)});
  329. break
  330. case 'change':
  331. try {
  332. _this.files = new Map([..._this.files,...JSON.parse(decodeURIComponent(files))]);
  333. } catch (e) {
  334. return console.error('出错了,请检查代码')
  335. }
  336. _this.onchange(_this.files);
  337. break
  338. case 'progress':
  339. try {
  340. item = JSON.parse(decodeURIComponent(item));
  341. } catch (e) {
  342. return console.error('出错了,请检查代码')
  343. }
  344. _this._changeFilesItem(item,end);
  345. break
  346. default:
  347. break
  348. }
  349. })
  350. }
  351. _getRequest(url) {
  352. let theRequest = new Object()
  353. let index = url.indexOf('?')
  354. if (index != -1) {
  355. let str = url.substring(index + 1)
  356. let strs = str.split('&')
  357. for (let i = 0; i < strs.length; i++) {
  358. theRequest[strs[i].split('=')[0]] = decodeURIComponent(strs[i].split('=')[1])
  359. }
  360. }
  361. return theRequest
  362. }
  363. _changeFilesItem(item,end=false) {
  364. this.debug&&console.log('onprogress',JSON.stringify(item));
  365. this.onprogress(item,end);
  366. this.files.set(item.name,item);
  367. }
  368. _uploadHandle(item) {
  369. item.type = 'loading';
  370. delete item.responseText;
  371. return new Promise((resolve,reject)=>{
  372. this.debug&&console.log('option',JSON.stringify(this.option));
  373. let {url,name,method='POST',header,formData} = this.option;
  374. let form = new FormData();
  375. for (let keys in formData) {
  376. form.append(keys, formData[keys])
  377. }
  378. form.append(name, item.file);
  379. let xmlRequest = new XMLHttpRequest();
  380. xmlRequest.open(method, url, true);
  381. for (let keys in header) {
  382. xmlRequest.setRequestHeader(keys, header[keys])
  383. }
  384. xmlRequest.upload.addEventListener(
  385. 'progress',
  386. event => {
  387. if (event.lengthComputable) {
  388. let progress = Math.ceil((event.loaded * 100) / event.total)
  389. if (progress <= 100) {
  390. item.progress = progress;
  391. this._changeFilesItem(item);
  392. }
  393. }
  394. },
  395. false
  396. );
  397. xmlRequest.ontimeout = () => {
  398. console.error('请求超时')
  399. item.type = 'fail';
  400. this._changeFilesItem(item,true);
  401. return resolve(false);
  402. }
  403. xmlRequest.onreadystatechange = ev => {
  404. if (xmlRequest.readyState == 4) {
  405. if (xmlRequest.status == 200) {
  406. this.debug&&console.log('上传完成:' + xmlRequest.responseText)
  407. item['responseText'] = xmlRequest.responseText;
  408. item.type = 'success';
  409. this._changeFilesItem(item,true);
  410. return resolve(true);
  411. } else if (xmlRequest.status == 0) {
  412. console.error('status = 0 :请检查请求头Content-Type与服务端是否匹配,服务端已正确开启跨域,并且nginx未拦截阻止请求')
  413. }
  414. console.error('--ERROR--:status = ' + xmlRequest.status)
  415. item.type = 'fail';
  416. this._changeFilesItem(item,true);
  417. return resolve(false);
  418. }
  419. }
  420. xmlRequest.send(form)
  421. });
  422. }
  423. _uploadHandleWX(item) {
  424. item.type = 'loading';
  425. delete item.responseText;
  426. return new Promise((resolve,reject)=>{
  427. this.debug&&console.log('option',JSON.stringify(this.option));
  428. let form = {filePath: item.path,...this.option };
  429. form['fail'] = ({ errMsg = '' }) => {
  430. console.error('--ERROR--:' + errMsg)
  431. item.type = 'fail';
  432. this._changeFilesItem(item,true);
  433. return resolve(false);
  434. }
  435. form['success'] = res => {
  436. if (res.statusCode == 200) {
  437. this.debug&&console.log('上传完成,微信端返回不一定是字符串,根据接口返回格式判断是否需要JSON.parse:' + res.data)
  438. item['responseText'] = res.data;
  439. item.type = 'success';
  440. this._changeFilesItem(item,true);
  441. return resolve(true);
  442. }
  443. item.type = 'fail';
  444. this._changeFilesItem(item,true);
  445. return resolve(false);
  446. }
  447. let xmlRequest = uni.uploadFile(form);
  448. xmlRequest.onProgressUpdate(({ progress = 0 }) => {
  449. if (progress <= 100) {
  450. item.progress = progress;
  451. this._changeFilesItem(item);
  452. }
  453. })
  454. });
  455. }
  456. }