LsjFile.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. this.files.set(file.name,{file,path,name: file.name,size: file.size,progress: 0,type: 'waiting'});
  143. return true;
  144. }
  145. }
  146. /**
  147. * 移除文件
  148. * @param {string}name 不传name默认移除所有文件,传入name移除指定name的文件
  149. */
  150. clear(name='') {
  151. // #ifdef APP-PLUS
  152. this.dom&&this.dom.evalJS(`vm.clear('${name}')`);
  153. // #endif
  154. if (!name) {
  155. this.files.clear();
  156. }
  157. else {
  158. this.files.delete(name);
  159. }
  160. return this.onchange(this.files);
  161. }
  162. /**
  163. * 提示框
  164. * @param {string}msg 轻提示内容
  165. */
  166. toast(msg) {
  167. uni.showToast({
  168. title: msg,
  169. icon: 'none'
  170. });
  171. }
  172. /**
  173. * 微信小程序选择文件
  174. * @param {number}count 可选择文件数量
  175. */
  176. chooseMessageFile(type,count) {
  177. wx.chooseMessageFile({
  178. count: count,
  179. type: type,
  180. success: ({ tempFiles }) => {
  181. for (let file of tempFiles) {
  182. this.addFile(file);
  183. }
  184. this._uploadAfter();
  185. },
  186. fail: () => {
  187. this.toast(`打开失败`);
  188. }
  189. })
  190. }
  191. _copyObject(obj) {
  192. if (typeof obj !== "undefined") {
  193. return JSON.parse(JSON.stringify(obj));
  194. } else {
  195. return obj;
  196. }
  197. }
  198. /**
  199. * 自动根据字符串路径设置对象中的值 支持.和[]
  200. * @param {Object} dataObj 数据源
  201. * @param {String} name 支持a.b 和 a[b]
  202. * @param {String} value 值
  203. * setValue(dataObj, name, value);
  204. */
  205. _setValue(dataObj, name, value) {
  206. // 通过正则表达式 查找路径数据
  207. let dataValue;
  208. if (typeof value === "object") {
  209. dataValue = this._copyObject(value);
  210. } else {
  211. dataValue = value;
  212. }
  213. let regExp = new RegExp("([\\w$]+)|\\[(:\\d)\\]", "g");
  214. const patten = name.match(regExp);
  215. // 遍历路径 逐级查找 最后一级用于直接赋值
  216. for (let i = 0; i < patten.length - 1; i++) {
  217. let keyName = patten[i];
  218. if (typeof dataObj[keyName] !== "object") dataObj[keyName] = {};
  219. dataObj = dataObj[keyName];
  220. }
  221. // 最后一级
  222. dataObj[patten[patten.length - 1]] = dataValue;
  223. this.debug&&console.log('参数更新后',JSON.stringify(this.option));
  224. }
  225. _uploadAfter() {
  226. this.onchange(this.files);
  227. setTimeout(()=>{
  228. this.instantly&&this.upload();
  229. },1000)
  230. }
  231. _overrideUrlLoading() {
  232. this.dom.overrideUrlLoading({ mode: 'reject' }, e => {
  233. let {retype,item,files,end} = this._getRequest(
  234. e.url
  235. );
  236. let _this = this;
  237. switch (retype) {
  238. case 'updateOption':
  239. this.dom.evalJS(`vm.setData('${JSON.stringify(_this.option)}')`);
  240. break
  241. case 'change':
  242. try {
  243. _this.files = new Map([..._this.files,...JSON.parse(unescape(files))]);
  244. } catch (e) {
  245. return console.error('出错了,请检查代码')
  246. }
  247. _this.onchange(_this.files);
  248. break
  249. case 'progress':
  250. try {
  251. item = JSON.parse(unescape(item));
  252. } catch (e) {
  253. return console.error('出错了,请检查代码')
  254. }
  255. _this._changeFilesItem(item,end);
  256. break
  257. default:
  258. break
  259. }
  260. })
  261. }
  262. _getRequest(url) {
  263. let theRequest = new Object()
  264. let index = url.indexOf('?')
  265. if (index != -1) {
  266. let str = url.substring(index + 1)
  267. let strs = str.split('&')
  268. for (let i = 0; i < strs.length; i++) {
  269. theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
  270. }
  271. }
  272. return theRequest
  273. }
  274. _changeFilesItem(item,end=false) {
  275. this.debug&&console.log('onprogress',JSON.stringify(item));
  276. this.onprogress(item,end);
  277. this.files.set(item.name,item);
  278. }
  279. _uploadHandle(item) {
  280. item.type = 'loading';
  281. delete item.responseText;
  282. return new Promise((resolve,reject)=>{
  283. this.debug&&console.log('option',JSON.stringify(this.option));
  284. let {url,name,method='POST',header,formData} = this.option;
  285. let form = new FormData();
  286. for (let keys in formData) {
  287. form.append(keys, formData[keys])
  288. }
  289. form.append(name, item.file);
  290. let xmlRequest = new XMLHttpRequest();
  291. xmlRequest.open(method, url, true);
  292. for (let keys in header) {
  293. xmlRequest.setRequestHeader(keys, header[keys])
  294. }
  295. xmlRequest.upload.addEventListener(
  296. 'progress',
  297. event => {
  298. if (event.lengthComputable) {
  299. let progress = Math.ceil((event.loaded * 100) / event.total)
  300. if (progress <= 100) {
  301. item.progress = progress;
  302. this._changeFilesItem(item);
  303. }
  304. }
  305. },
  306. false
  307. );
  308. xmlRequest.ontimeout = () => {
  309. console.error('请求超时')
  310. item.type = 'fail';
  311. this._changeFilesItem(item,true);
  312. return resolve(false);
  313. }
  314. xmlRequest.onreadystatechange = ev => {
  315. if (xmlRequest.readyState == 4) {
  316. if (xmlRequest.status == 200) {
  317. this.debug&&console.log('上传完成:' + xmlRequest.responseText)
  318. item['responseText'] = xmlRequest.responseText;
  319. item.type = 'success';
  320. this._changeFilesItem(item,true);
  321. return resolve(true);
  322. } else if (xmlRequest.status == 0) {
  323. console.error('status = 0 :请检查请求头Content-Type与服务端是否匹配,服务端已正确开启跨域,并且nginx未拦截阻止请求')
  324. }
  325. console.error('--ERROR--:status = ' + xmlRequest.status)
  326. item.type = 'fail';
  327. this._changeFilesItem(item,true);
  328. return resolve(false);
  329. }
  330. }
  331. xmlRequest.send(form)
  332. });
  333. }
  334. _uploadHandleWX(item) {
  335. item.type = 'loading';
  336. delete item.responseText;
  337. return new Promise((resolve,reject)=>{
  338. this.debug&&console.log('option',JSON.stringify(this.option));
  339. let form = {filePath: item.file.path,...this.option };
  340. form['fail'] = ({ errMsg = '' }) => {
  341. console.error('--ERROR--:' + errMsg)
  342. item.type = 'fail';
  343. this._changeFilesItem(item,true);
  344. return resolve(false);
  345. }
  346. form['success'] = res => {
  347. if (res.statusCode == 200) {
  348. this.debug&&console.log('上传完成,微信端返回不一定是字符串,根据接口返回格式判断是否需要JSON.parse:' + res.data)
  349. item['responseText'] = res.data;
  350. item.type = 'success';
  351. this._changeFilesItem(item,true);
  352. return resolve(true);
  353. }
  354. item.type = 'fail';
  355. this._changeFilesItem(item,true);
  356. return resolve(false);
  357. }
  358. let xmlRequest = uni.uploadFile(form);
  359. xmlRequest.onProgressUpdate(({ progress = 0 }) => {
  360. if (progress <= 100) {
  361. item.progress = progress;
  362. this._changeFilesItem(item);
  363. }
  364. })
  365. });
  366. }
  367. }