LsjFile.js 10 KB

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