Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

392 linhas
9.7 KiB

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