upload.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import store from '@/store'
  2. import config from '@/config'
  3. import { getAccessToken } 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 + config.baseApi;
  8. const upload = config => {
  9. // 是否需要设置 token
  10. const isToken = (config.headers || {}).isToken === false
  11. config.header = config.header || {}
  12. if (getAccessToken() && !isToken) {
  13. config.header['Authorization'] = 'Bearer ' + getAccessToken()
  14. }
  15. // get请求映射params参数
  16. if (config.params) {
  17. let url = config.url + '?' + tansParams(config.params)
  18. url = url.slice(0, -1)
  19. config.url = url
  20. }
  21. // 设置租户 TODO 芋艿:强制 1 先
  22. config.header['tenant-id'] = '293';
  23. return new Promise((resolve, reject) => {
  24. uni.uploadFile({
  25. timeout: config.timeout || timeout,
  26. url: baseUrl + config.url,
  27. filePath: config.filePath,
  28. name: config.name || 'file',
  29. header: config.header,
  30. formData: config.formData,
  31. method: config.method || 'post',
  32. success: (res) => {
  33. let result = JSON.parse(res.data)
  34. const code = result.code || 200
  35. const msg = errorCode[code] || result.msg || errorCode['default']
  36. if (code === 200) {
  37. resolve(result)
  38. } else if (code == 401) {
  39. store.dispatch('LogOut').then(res => {
  40. uni.reLaunch({ url: '/' })
  41. })
  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. } else if (code === 500) {
  51. toast(msg)
  52. reject('500')
  53. } else if (code !== 200) {
  54. toast(msg)
  55. reject(code)
  56. }
  57. },
  58. fail: (error) => {
  59. let { message } = error
  60. if (message == 'Network Error') {
  61. message = '后端接口连接异常'
  62. } else if (message.includes('timeout')) {
  63. message = '系统接口请求超时'
  64. } else if (message.includes('Request failed with status code')) {
  65. message = '系统接口' + message.substr(message.length - 3) + '异常'
  66. }
  67. toast(message)
  68. reject(error)
  69. }
  70. })
  71. })
  72. }
  73. export default upload