upload.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. const Clientid = config.Clientid
  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. config.header['Clientid'] = Clientid
  16. }
  17. // get请求映射params参数
  18. if (config.params) {
  19. let url = config.url + '?' + tansParams(config.params)
  20. url = url.slice(0, -1)
  21. config.url = url
  22. }
  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. success: (res) => {
  32. let result = JSON.parse(res.data)
  33. const code = result.code || 200
  34. const msg = errorCode[code] || result.msg || errorCode['default']
  35. if (code === 200) {
  36. resolve(result)
  37. } else if (code == 401) {
  38. showConfirm("登录状态已过期,您可以继续留在该页面,或者重新登录?").then(res => {
  39. if (res.confirm) {
  40. store.dispatch('LogOut').then(res => {
  41. uni.reLaunch({ url: '/pages/login' })
  42. })
  43. }
  44. })
  45. reject('无效的会话,或者会话已过期,请重新登录。')
  46. } else if (code === 500) {
  47. toast(msg)
  48. reject('500')
  49. } else if (code !== 200) {
  50. toast(msg)
  51. reject(code)
  52. }
  53. },
  54. fail: (error) => {
  55. let { message } = error
  56. if (message == 'Network Error') {
  57. message = '后端接口连接异常'
  58. } else if (message.includes('timeout')) {
  59. message = '系统接口请求超时'
  60. } else if (message.includes('Request failed with status code')) {
  61. message = '系统接口' + message.substr(message.length - 3) + '异常'
  62. }
  63. toast(message)
  64. reject(error)
  65. }
  66. })
  67. })
  68. }
  69. export default upload