LsjFile.js 10 KB

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