LsjFile.js 11 KB

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