upload.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import store from '@/store'
  2. import config from '@/config'
  3. import {
  4. getToken
  5. } from '@/utils/auth'
  6. import errorCode from '@/utils/errorCode'
  7. import {
  8. toast,
  9. showConfirm,
  10. tansParams
  11. } from '@/utils/common'
  12. let timeout = 10000
  13. const baseUrl = config.baseUrl
  14. const upload = config => {
  15. // 是否需要设置 token
  16. const isToken = (config.headers || {}).isToken === false
  17. config.header = config.header || {}
  18. if (getToken() && !isToken) {
  19. config.header['Authorization'] = 'Bearer ' + getToken()
  20. }
  21. // get请求映射params参数
  22. if (config.params) {
  23. let url = config.url + '?' + tansParams(config.params)
  24. url = url.slice(0, -1)
  25. config.url = url
  26. }
  27. return new Promise((resolve, reject) => {
  28. uni.uploadFile({
  29. timeout: config.timeout || timeout,
  30. url: baseUrl + config.url,
  31. filePath: config.filePath,
  32. name: config.name || 'file',
  33. header: config.header,
  34. formData: config.formData,
  35. success: (res) => {
  36. let result = JSON.parse(res.data)
  37. const code = result.code || 200
  38. const msg = errorCode[code] || result.msg || errorCode['default']
  39. if (code === 200) {
  40. resolve(result)
  41. } else if (code == 401) {
  42. // showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  43. // if (res.confirm) {
  44. // store.dispatch('LogOut').then(res => {
  45. // uni.reLaunch({ url: '/pages/login' })
  46. // })
  47. // }
  48. // })
  49. // reject('无效的会话,或者会话已过期,请重新登录。')
  50. let loginForm = {
  51. username: uni.getStorageSync('u1'),
  52. password: uni.getStorageSync('p1'),
  53. code: "",
  54. uuid: ''
  55. }
  56. getCurrentPages()[0].$vm.$store.dispatch('Login', loginForm).then(() => {}).catch((error) => {
  57. showConfirm('自动重登失效,您可以继续留在该页面,或者手动登录?').then(res => {
  58. if (res.confirm) {
  59. store.dispatch('LogOut').then(res => {
  60. uni.reLaunch({
  61. url: '/pages/login'
  62. })
  63. })
  64. }
  65. })
  66. uni.showToast({
  67. title: "",
  68. icon: 'none',
  69. duration: 0
  70. });
  71. });
  72. } else if (code === 500) {
  73. toast(msg)
  74. reject('500')
  75. } else if (code !== 200) {
  76. toast(msg)
  77. reject(code)
  78. }
  79. },
  80. fail: (error) => {
  81. let {
  82. message
  83. } = error
  84. if (message == 'Network Error') {
  85. message = '后端接口连接异常'
  86. } else if (message.includes('timeout')) {
  87. message = '系统接口请求超时'
  88. } else if (message.includes('Request failed with status code')) {
  89. message = '系统接口' + message.substr(message.length - 3) + '异常'
  90. }
  91. toast(message)
  92. reject(error)
  93. }
  94. })
  95. })
  96. }
  97. export default upload