common.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. import store from '@/store'
  2. import config from '@/config'
  3. import { getToken } from '@/utils/auth'
  4. import errorCode from '@/utils/errorCode'
  5. // import { toast, showConfirm, tansParams } from '@/utils/common'
  6. let timeout = 10000
  7. const baseUrl = config.baseUrl
  8. /**
  9. * 显示消息提示框
  10. * @param content 提示的标题
  11. */
  12. export function toast(content) {
  13. uni.showToast({
  14. icon: 'none',
  15. title: content
  16. })
  17. }
  18. /**
  19. * 显示模态弹窗
  20. * @param content 提示的标题
  21. */
  22. export function showConfirm(content) {
  23. return new Promise((resolve, reject) => {
  24. uni.showModal({
  25. title: '提示',
  26. content: content,
  27. cancelText: '取消',
  28. confirmText: '确定',
  29. success: function(res) {
  30. resolve(res)
  31. }
  32. })
  33. })
  34. }
  35. // 字典值匹配
  36. export function selectDictLabel(datas, value) {
  37. var actions = [];
  38. Object.keys(datas).some((key) => {
  39. // if (datas[key].dictValue == ('' + value)) {
  40. // actions.push(datas[key].dictLabel);
  41. // return true;
  42. // }
  43. if (datas[key].dictLabel == ('' + value)) {
  44. actions.push(datas[key].dictValue);
  45. return true;
  46. }
  47. })
  48. return actions.join('');
  49. }
  50. export function selectDictValue(datas, value) {
  51. var actions = [];
  52. Object.keys(datas).some((key) => {
  53. if (datas[key].dictValue == ('' + value)) {
  54. actions.push(datas[key].dictLabel);
  55. return true;
  56. }
  57. })
  58. return actions.join('');
  59. }
  60. /**
  61. * 参数处理
  62. * @param params 参数
  63. */
  64. export function tansParams(params) {
  65. let result = ''
  66. for (const propName of Object.keys(params)) {
  67. const value = params[propName]
  68. var part = encodeURIComponent(propName) + "="
  69. if (value !== null && value !== "" && typeof (value) !== "undefined") {
  70. if (typeof value === 'object') {
  71. for (const key of Object.keys(value)) {
  72. if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
  73. let params = propName + '[' + key + ']'
  74. var subPart = encodeURIComponent(params) + "="
  75. result += subPart + encodeURIComponent(value[key]) + "&"
  76. }
  77. }
  78. } else {
  79. result += part + encodeURIComponent(value) + "&"
  80. }
  81. }
  82. }
  83. return result
  84. }
  85. // 上传
  86. //上传图片
  87. export function uploadmore(api, filePaths, successUp, failUp, i, length, files, callback) {
  88. const isToken = (config.headers || {}).isToken === false
  89. config.header = config.header || {}
  90. if (getToken() && !isToken) {
  91. config.header['Authorization'] = 'Bearer ' + getToken()
  92. }
  93. // get请求映射params参数
  94. if (config.params) {
  95. let url = config.url + '?' + tansParams(config.params)
  96. url = url.slice(0, -1)
  97. config.url = url
  98. }
  99. uni.showLoading({
  100. title: '上传中'
  101. })
  102. var failfile = [];
  103. uni.uploadFile({
  104. timeout: config.timeout || timeout,
  105. url: baseUrl + api, //仅为示例,非真实的接口地址
  106. filePath: filePaths[i],
  107. name: 'file',
  108. header: config.header,
  109. formData: config.formData,
  110. success: function(resp) {
  111. uni.hideLoading();
  112. let result = JSON.parse(resp.data)
  113. const code = result.code || 200
  114. const msg = errorCode[code] || result.msg || errorCode['default']
  115. // console.log(result.fileName,8)
  116. if (result.code == 200) {
  117. successUp++;
  118. files[i] = result.fileName;
  119. } else if(result.code==401) {
  120. showConfirm("登录状态已过期,您可以继续留在该页面,或者重新登录?").then(res => {
  121. if (res.confirm) {
  122. store.dispatch('LogOut').then(res => {
  123. uni.reLaunch({ url: '/pages/login/login' })
  124. })
  125. }
  126. })
  127. callback('无效的会话,或者会话已过期,请重新登录。');
  128. }else{
  129. failfile = failfile.concat(filePaths[i])
  130. failUp++;
  131. }
  132. },
  133. fail: function(res) {
  134. uni.hideLoading();
  135. failfile = failfile.concat(filePaths[i])
  136. failUp++;
  137. },
  138. complete: function(rsp) {
  139. // console.log(rsp, filePaths[i])
  140. uni.hideLoading();
  141. i++;
  142. if (i == length) {
  143. uni.showToast({
  144. title: '总共' + successUp + '张上传成功,' + failUp + '张上传失败!',
  145. icon: 'none',
  146. duration: 2000
  147. });
  148. callback(files);
  149. } else { //递归调用upload函数
  150. uploadmore(api, filePaths, successUp, failUp, i, length, files, callback);
  151. }
  152. }
  153. });
  154. }
  155. export function clickPeople(e){//点击下载
  156. let _this = this;
  157. //下载地址
  158. var downloadUlr = e;
  159. //获取地址后缀
  160. var suffix = e.split(".")[e.split(".").length - 1];
  161. //判断是否为(图片或视频)
  162. if(e.substring(e.length - 3) == "MP4" || e.substring(e.length - 3) == "mp4" || e.substring(e.length - 3) == "jpg" || e.substring(e.length - 3) == "png"){
  163. const downloadTask = uni.downloadFile({
  164. url:e,
  165. success: res => {
  166. if (res.statusCode === 200) {
  167. if(res.tempFilePath.substring(res.tempFilePath.length - 3) == "mp4" || res.tempFilePath.substring(res.tempFilePath.length - 3) == "MP4"){//视频
  168. //保存视频到相册
  169. uni.saveVideoToPhotosAlbum({
  170. filePath: res.tempFilePath,
  171. success: function () {
  172. uni.showToast({
  173. title: '保存成功',
  174. icon: 'none',
  175. duration:2000,
  176. mask:true
  177. });
  178. },
  179. fail: function() {
  180. // this.loadProgress = 0;
  181. uni.showToast({
  182. title: '保存失败',
  183. icon: 'none'
  184. });
  185. }
  186. });
  187. }else{//图片
  188. // 图片保存到手机相册
  189. uni.saveImageToPhotosAlbum({
  190. filePath: res.tempFilePath,
  191. success: function() {
  192. uni.showToast({
  193. title: '保存成功',
  194. icon: 'none',
  195. duration:2000,
  196. mask:true
  197. });
  198. },
  199. fail: function() {
  200. // this.loadProgress = 0;
  201. uni.showToast({
  202. title: '保存失败',
  203. icon: 'none'
  204. });
  205. }
  206. });
  207. }
  208. }else{
  209. uni.showToast({
  210. title:'下载失败',
  211. icon:"none"
  212. })
  213. }
  214. },
  215. fail:(err) => {
  216. // this.loadProgress = 0;
  217. uni.showToast({
  218. icon:"none",
  219. mask:true,
  220. title:'下载失败'
  221. })
  222. }
  223. });
  224. // downloadTask.onProgressUpdate((res) => {
  225. // this.loadProgress = res.progress;
  226. // if (this.loadProgress < 100) {
  227. // } else {
  228. // this.loadProgress = 0;
  229. // }
  230. // if(res.totalBytesExpectedToWrite < 10485760){
  231. // this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1024) + "KB";
  232. // this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1024) + "KB";
  233. // this.dltDownLvWc = res.progress + "%"
  234. // }else{
  235. // this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1048576) + "M"
  236. // this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1048576) + "M";
  237. // this.dltDownLvWc = res.progress + "%"
  238. // }
  239. // });
  240. }else{
  241. //下载文件为非图片和视频的文件
  242. let _this = this;
  243. const downloadTaskt = uni.downloadFile({
  244. url:e,//下载地址接口返回
  245. success:(data) => {
  246. uni.hideLoading()
  247. if(data.statusCode === 200){
  248. var sFilePath = data.tempFilePath
  249. var sFileName = downloadUlr.split('/')[downloadUlr.split('/').length - 1];//原来的文件名
  250. //#ifdef APP-PLUS
  251. //文件保存到本地
  252. uni.saveFile({
  253. tempFilePath: data.tempFilePath,//临时路径
  254. success:function(res){
  255. var savedFilePath = res.savedFilePath;
  256. let osname = plus.os.name;
  257. //ios手机直接打开文件,手动存储文件到手机,Android手机从根目录创建文件夹,保存文件并改名
  258. if (osname == 'Android') {
  259. uni.showToast({
  260. icon:'none',
  261. mask:true,
  262. title:'保存成功1',
  263. duration:1000,
  264. });
  265. // _this.fSetFileName(, sFilePath,e);
  266. // fSetFileName(sFilePath, sFileName,urls)
  267. // var =
  268. var sFileNames = res.savedFilePath.split('/')[res.savedFilePath.split('/').length - 1];//原来的文件名
  269. var aFileUrl = sFilePath.split('/').splice(0, sFilePath.split('/').length - 1);//saveFile API保存的本地地址
  270. var url = downloadUlr;//下载地址
  271. // 'url下载地址(和上面的一样)'
  272. let dtask = plus.downloader.createDownload(url, {
  273. filename: "file://storage/emulated/0/Download/" + sFileNames //在手机存储更目录创建一个叫AAA的文件夹,把文件存储进去,并更改会原名
  274. },
  275. (d, status) => {
  276. console.log(status,77)
  277. if (status == 200) {
  278. let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
  279. console.log(fileSaveUrl,99)
  280. } else {
  281. //下载失败
  282. plus.downloader.clear(); //清除下载任务
  283. }
  284. })
  285. dtask.start();
  286. }
  287. setTimeout(() => {
  288. //打开文档查看
  289. uni.openDocument({
  290. filePath:res.savedFilePath,
  291. success:function(res){
  292. // console.log("成功打开文件")
  293. },
  294. fail(){
  295. // console.log("打开文件失败")
  296. }
  297. })
  298. },1000)
  299. },
  300. fail:function(res){
  301. }
  302. });
  303. //#endif
  304. //#ifdef MP-WEIXIN
  305. //小程序对文件下载并不友好,不建议使用小程序当做下载器
  306. const FileSystemManager = wx.getFileSystemManager();
  307. FileSystemManager.saveFile({//下载成功后保存到本地
  308. tempFilePath:data.tempFilePath,
  309. filePath:wx.env.USER_DATA_PATH + "/" + sFileName,
  310. success(res2){
  311. if(res2.errMsg == 'saveFile:ok'){
  312. // 判断手机平台是 Android 还是 IOS
  313. if (uni.getSystemInfoSync().platform === 'android') {
  314. // console.log('运行Android上')
  315. uni.showModal({
  316. title:"保存地址为",
  317. content:"手机存储/Android/data/com.tencent.mm/MicroMsg/wxanewfiles"
  318. })
  319. } else {
  320. // console.log('运行iOS上')
  321. uni.showToast({
  322. title:"请转移APP下载",
  323. icon:"none"
  324. })
  325. }
  326. }else{
  327. uni.showToast({
  328. title:"下载失败",
  329. icon:"none"
  330. })
  331. }
  332. },
  333. fail(){
  334. uni.showToast({
  335. title:"下载失败",
  336. icon:"none"
  337. })
  338. }
  339. })
  340. //#endif
  341. }else{
  342. this.loadProgress = 0;
  343. uni.showToast({
  344. icon:"none",
  345. mask:true,
  346. title:"下载失败"
  347. })
  348. }
  349. },
  350. fail:(err) => {
  351. this.arcZzShow = false;
  352. this.loadProgress = 0;
  353. uni.showToast({
  354. icon:"none",
  355. mask:true,
  356. title:"下载失败"
  357. })
  358. }
  359. })
  360. // downloadTaskt.onProgressUpdate((res) => {
  361. // this.loadProgress = res.progress;
  362. // if (this.loadProgress < 100) {
  363. // } else {
  364. // this.loadProgress = 0;
  365. // }
  366. // if(res.totalBytesExpectedToWrite < 10485760){
  367. // this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1024) + "KB";
  368. // this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1024) + "KB";
  369. // this.dltDownLvWc = res.progress + "%"
  370. // }else{
  371. // this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1048576) + "M"
  372. // this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1048576) + "M";
  373. // this.dltDownLvWc = res.progress + "%"
  374. // }
  375. // });
  376. }
  377. }
  378. // 下载改名
  379. export function fSetFileName(sFilePath, sFileName,urls) {
  380. var sFileName = sFileName.split('/')[sFileName.split('/').length - 1];//原来的文件名
  381. var aFileUrl = sFilePath.split('/').splice(0, sFilePath.split('/').length - 1);//saveFile API保存的本地地址
  382. var url = urls;//下载地址
  383. // 'url下载地址(和上面的一样)'
  384. let dtask = plus.downloader.createDownload(url, {
  385. filename: "file://storage/emulated/0/AAA/" + sFileName //在手机存储更目录创建一个叫AAA的文件夹,把文件存储进去,并更改会原名
  386. },
  387. (d, status) => {
  388. console.log(status,77)
  389. if (status == 200) {
  390. let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
  391. console.log(fileSaveUrl,99)
  392. } else {
  393. //下载失败
  394. plus.downloader.clear(); //清除下载任务
  395. }
  396. })
  397. dtask.start();
  398. }