upload.js 2.4 KB

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