upload.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 baseUrl1 = config.baseUrl1
  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. // 支持自定义 baseUrl,如果没有指定则使用默认的 baseUrl
  23. const uploadBaseUrl = config.baseUrl || baseUrl
  24. return new Promise((resolve, reject) => {
  25. uni.uploadFile({
  26. timeout: config.timeout || timeout,
  27. url: uploadBaseUrl + config.url,
  28. filePath: config.filePath,
  29. name: config.name || 'file',
  30. header: config.header,
  31. formData: config.formData,
  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. showConfirm("登录状态已过期,您可以继续留在该页面,或者重新登录?").then(res => {
  40. if (res.confirm) {
  41. store.dispatch('LogOut').then(res => {
  42. uni.reLaunch({ url: '/pages/login/login' })
  43. })
  44. }
  45. })
  46. reject('无效的会话,或者会话已过期,请重新登录。')
  47. } else if (code === 500) {
  48. toast(msg)
  49. reject('500')
  50. } else if (code !== 200) {
  51. toast(msg)
  52. reject(code)
  53. }
  54. },
  55. fail: (error) => {
  56. let { message } = error
  57. if (message == 'Network Error') {
  58. message = '后端接口连接异常'
  59. } else if (message.includes('timeout')) {
  60. message = '系统接口请求超时'
  61. } else if (message.includes('Request failed with status code')) {
  62. message = '系统接口' + message.substr(message.length - 3) + '异常'
  63. }
  64. toast(message)
  65. reject(error)
  66. }
  67. })
  68. })
  69. }
  70. export default upload