upload.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 serverAddress = uni.getStorageSync('serverAddress')
  14. const baseUrlIp = serverAddress ? serverAddress : config.baseUrl
  15. const baseUrl = baseUrlIp + '/projects/outApi'
  16. const upload = config => {
  17. // 是否需要设置 token
  18. const isToken = (config.headers || {}).isToken === false
  19. config.header = config.header || {}
  20. if (getToken() && !isToken) {
  21. config.header['Authorization'] = 'Bearer ' + getToken()
  22. }
  23. // get请求映射params参数
  24. if (config.params) {
  25. let url = config.url + '?' + tansParams(config.params)
  26. url = url.slice(0, -1)
  27. config.url = url
  28. }
  29. return new Promise((resolve, reject) => {
  30. uni.uploadFile({
  31. timeout: config.timeout || timeout,
  32. url: baseUrl + config.url,
  33. filePath: config.filePath,
  34. name: config.name || 'file',
  35. header: config.header,
  36. formData: config.formData,
  37. success: (res) => {
  38. let result = JSON.parse(res.data)
  39. const code = result.code || 200
  40. const msg = errorCode[code] || result.msg || errorCode['default']
  41. if (code === 200) {
  42. resolve(result)
  43. } else if (code == 401) {
  44. showConfirm("登录状态已过期,您可以继续留在该页面,或者重新登录?").then(res => {
  45. if (res.confirm) {
  46. store.dispatch('LogOut').then(res => {
  47. uni.reLaunch({
  48. url: '/pages/login/login'
  49. })
  50. })
  51. }
  52. })
  53. reject('无效的会话,或者会话已过期,请重新登录。')
  54. } else if (code === 500) {
  55. toast(msg)
  56. reject('500')
  57. } else if (code !== 200) {
  58. toast(msg)
  59. reject(code)
  60. }
  61. },
  62. fail: (error) => {
  63. let {
  64. message
  65. } = error
  66. if (message == 'Network Error') {
  67. message = '后端接口连接异常'
  68. } else if (message.includes('timeout')) {
  69. message = '系统接口请求超时'
  70. } else if (message.includes('Request failed with status code')) {
  71. message = '系统接口' + message.substr(message.length - 3) + '异常'
  72. }
  73. toast(message)
  74. reject(error)
  75. }
  76. })
  77. })
  78. }
  79. export default upload