LsjFile.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 = 900
  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. } else {
  86. this._setValue(this.option, name, value);
  87. }
  88. this.debug && console.log(JSON.stringify(this.option));
  89. // #ifdef APP-PLUS
  90. this.dom.evalJS(`vm.setData('${JSON.stringify(this.option)}')`);
  91. // #endif
  92. }
  93. /**
  94. * 上传
  95. * @param {string}name 文件名称
  96. */
  97. async upload(name = '') {
  98. if (!this.option.url) {
  99. throw Error('未设置上传地址');
  100. }
  101. // #ifndef APP-PLUS
  102. if (name && this.files.has(name)) {
  103. await this.uploadHandle(this.files.get(name));
  104. } else {
  105. for (let item of this.files.values()) {
  106. if (item.type === 'waiting' || item.type === 'fail') {
  107. await this.uploadHandle(item);
  108. }
  109. }
  110. }
  111. // #endif
  112. // #ifdef APP-PLUS
  113. this.dom && this.dom.evalJS(`vm.upload('${name}')`);
  114. // #endif
  115. }
  116. // 选择文件change
  117. addFile(file, isCallChange) {
  118. let name = file.name;
  119. this.debug && console.log('文件名称', name, '大小', file.size);
  120. if (file) {
  121. // 限制文件格式
  122. let path = '';
  123. let suffix = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
  124. let formats = this.prohibited.formats.toLowerCase();
  125. // #ifndef MP-WEIXIN
  126. path = URL.createObjectURL(file);
  127. // #endif
  128. // #ifdef MP-WEIXIN
  129. path = file.path;
  130. // #endif
  131. if (formats && !formats.includes(suffix)) {
  132. this.toast(`不支持上传${suffix.toUpperCase()}格式文件`);
  133. return false;
  134. }
  135. // 限制文件大小
  136. if (file.size > 1024 * 1024 * Math.abs(this.prohibited.size)) {
  137. this.toast(`文件大小超过${this.prohibited.size}MB`)
  138. return false;
  139. }
  140. this.files.set(file.name, {
  141. file,
  142. path,
  143. name: file.name,
  144. size: file.size,
  145. progress: 0,
  146. type: 'waiting'
  147. });
  148. return true;
  149. }
  150. }
  151. /**
  152. * 移除文件
  153. * @param {string}name 不传name默认移除所有文件,传入name移除指定name的文件
  154. */
  155. clear(name = '') {
  156. // #ifdef APP-PLUS
  157. this.dom && this.dom.evalJS(`vm.clear('${name}')`);
  158. // #endif
  159. if (!name) {
  160. this.files.clear();
  161. } else {
  162. this.files.delete(name);
  163. }
  164. return this.onchange(this.files);
  165. }
  166. /**
  167. * 提示框
  168. * @param {string}msg 轻提示内容
  169. */
  170. toast(msg) {
  171. uni.showToast({
  172. title: msg,
  173. icon: 'none'
  174. });
  175. }
  176. /**
  177. * 微信小程序选择文件
  178. * @param {number}count 可选择文件数量
  179. */
  180. chooseMessageFile(type, count) {
  181. wx.chooseMessageFile({
  182. count: count,
  183. type: type,
  184. success: ({
  185. tempFiles
  186. }) => {
  187. for (let file of tempFiles) {
  188. this.addFile(file);
  189. }
  190. this._uploadAfter();
  191. },
  192. fail: () => {
  193. this.toast(`打开失败`);
  194. }
  195. })
  196. }
  197. _copyObject(obj) {
  198. if (typeof obj !== "undefined") {
  199. return JSON.parse(JSON.stringify(obj));
  200. } else {
  201. return obj;
  202. }
  203. }
  204. /**
  205. * 自动根据字符串路径设置对象中的值 支持.和[]
  206. * @param {Object} dataObj 数据源
  207. * @param {String} name 支持a.b 和 a[b]
  208. * @param {String} value 值
  209. * setValue(dataObj, name, value);
  210. */
  211. _setValue(dataObj, name, value) {
  212. // 通过正则表达式 查找路径数据
  213. let dataValue;
  214. if (typeof value === "object") {
  215. dataValue = this._copyObject(value);
  216. } else {
  217. dataValue = value;
  218. }
  219. let regExp = new RegExp("([\\w$]+)|\\[(:\\d)\\]", "g");
  220. const patten = name.match(regExp);
  221. // 遍历路径 逐级查找 最后一级用于直接赋值
  222. for (let i = 0; i < patten.length - 1; i++) {
  223. let keyName = patten[i];
  224. if (typeof dataObj[keyName] !== "object") dataObj[keyName] = {};
  225. dataObj = dataObj[keyName];
  226. }
  227. // 最后一级
  228. dataObj[patten[patten.length - 1]] = dataValue;
  229. this.debug && console.log('参数更新后', JSON.stringify(this.option));
  230. }
  231. _uploadAfter() {
  232. this.onchange(this.files);
  233. setTimeout(() => {
  234. this.instantly && this.upload();
  235. }, 1000)
  236. }
  237. _overrideUrlLoading() {
  238. this.dom.overrideUrlLoading({
  239. mode: 'reject'
  240. }, e => {
  241. let {
  242. retype,
  243. item,
  244. files,
  245. end
  246. } = 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 {
  298. url,
  299. name,
  300. method = 'POST',
  301. header,
  302. formData,
  303. data
  304. } = this.option;
  305. let form = new FormData();
  306. for (let keys in formData) {
  307. form.append(keys, formData[keys])
  308. }
  309. for (let keys in data) {
  310. form.append(keys, data[keys])
  311. }
  312. form.append(name, item.file);
  313. let xmlRequest = new XMLHttpRequest();
  314. xmlRequest.open(method, url, true);
  315. for (let keys in header) {
  316. xmlRequest.setRequestHeader(keys, header[keys])
  317. }
  318. xmlRequest.upload.addEventListener(
  319. 'progress',
  320. event => {
  321. if (event.lengthComputable) {
  322. let progress = Math.ceil((event.loaded * 100) / event.total)
  323. if (progress <= 100) {
  324. item.progress = progress;
  325. this._changeFilesItem(item);
  326. }
  327. }
  328. },
  329. false
  330. );
  331. xmlRequest.ontimeout = () => {
  332. console.error('请求超时')
  333. item.type = 'fail';
  334. this._changeFilesItem(item, true);
  335. return resolve(false);
  336. }
  337. xmlRequest.onreadystatechange = ev => {
  338. if (xmlRequest.readyState == 4) {
  339. if (xmlRequest.status == 200) {
  340. this.debug && console.log('上传完成:' + xmlRequest.responseText)
  341. item['responseText'] = xmlRequest.responseText;
  342. item.type = 'success';
  343. this._changeFilesItem(item, true);
  344. return resolve(true);
  345. } else if (xmlRequest.status == 0) {
  346. console.error(
  347. 'status = 0 :请检查请求头Content-Type与服务端是否匹配,服务端已正确开启跨域,并且nginx未拦截阻止请求')
  348. }
  349. console.error('--ERROR--:status = ' + xmlRequest.status)
  350. item.type = 'fail';
  351. this._changeFilesItem(item, true);
  352. return resolve(false);
  353. }
  354. }
  355. xmlRequest.send(form)
  356. });
  357. }
  358. _uploadHandleWX(item) {
  359. item.type = 'loading';
  360. delete item.responseText;
  361. return new Promise((resolve, reject) => {
  362. this.debug && console.log('option', JSON.stringify(this.option));
  363. let form = {
  364. filePath: item.file.path,
  365. ...this.option,
  366. formData: this.option.data || {},
  367. };
  368. form['fail'] = ({
  369. errMsg = ''
  370. }) => {
  371. console.error('--ERROR--:' + errMsg)
  372. item.type = 'fail';
  373. this._changeFilesItem(item, true);
  374. return resolve(false);
  375. }
  376. form['success'] = res => {
  377. if (res.statusCode == 200) {
  378. this.debug && console.log('上传完成,微信端返回不一定是字符串,根据接口返回格式判断是否需要JSON.parse:' + res.data)
  379. item['responseText'] = res.data;
  380. item.type = 'success';
  381. this._changeFilesItem(item, true);
  382. return resolve(true);
  383. }
  384. item.type = 'fail';
  385. this._changeFilesItem(item, true);
  386. return resolve(false);
  387. }
  388. let xmlRequest = uni.uploadFile(form);
  389. xmlRequest.onProgressUpdate(({
  390. progress = 0
  391. }) => {
  392. if (progress <= 100) {
  393. item.progress = progress;
  394. this._changeFilesItem(item);
  395. }
  396. })
  397. });
  398. }
  399. }