upload.js 2.6 KB

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