upload.js 2.3 KB

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