LsjFile.js 10KB

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