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 upload = config => {
  9. // 是否需要设置 token
  10. const isToken = (config.headers || {}).isToken === false
  11. config.header = config.header || {}
  12. if (getToken() && !isToken) {
  13. config.header['Authorization'] = 'Bearer ' + getToken()
  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. return new Promise((resolve, reject) => {
  22. uni.uploadFile({
  23. timeout: config.timeout || timeout,
  24. url: baseUrl + config.url,
  25. filePath: config.filePath,
  26. name: config.name || 'file',
  27. header: config.header,
  28. formData: config.formData,
  29. success: (res) => {
  30. console.log(res,9)
  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("登录状态已过期,您可以继续留在该页面,或者重新登录?").then(res => {
  38. if (res.confirm) {
  39. store.dispatch('LogOut').then(res => {
  40. uni.reLaunch({ url: '/pages/login/login' })
  41. })
  42. }
  43. })
  44. reject('无效的会话,或者会话已过期,请重新登录。')
  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. console.log(error,10)
  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