upload.js 2.2 KB

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