83 lines
2.8 KiB
TypeScript
83 lines
2.8 KiB
TypeScript
import config from '@/config'
|
||
import { getToken } from '@/utils/auth'
|
||
import errorCode from '@/utils/errorCode'
|
||
import { toast, showConfirm, tansParams } from '@/utils/common'
|
||
import { ResponseData, RequestUploadConfig } from '@/types/request'
|
||
import useUserStore from '@/store/modules/user'
|
||
|
||
let timeout = 10000
|
||
const baseUrl = config.baseUrl
|
||
|
||
const upload = <T>(config: RequestUploadConfig): Promise<ResponseData<T>> => {
|
||
// 是否需要设置 token
|
||
const isToken = (config.headers || {}).isToken === false
|
||
config.header = config.header || {}
|
||
if (getToken() && !isToken) {
|
||
config.header['Authorization'] = 'Bearer ' + getToken()
|
||
}
|
||
// get请求映射params参数
|
||
if (config.params) {
|
||
let url = config.url + '?' + tansParams(config.params)
|
||
url = url.slice(0, -1)
|
||
config.url = url
|
||
}
|
||
const userStore = useUserStore()
|
||
return new Promise((resolve, reject) => {
|
||
uni.uploadFile({
|
||
timeout: config.timeout || timeout,
|
||
url: baseUrl + config.url,
|
||
filePath: config.filePath,
|
||
name: config.name || 'file',
|
||
header: config.header,
|
||
formData: config.formData,
|
||
success: (res) => {
|
||
let result
|
||
// 后端可能返回 JSON 字符串(正常)或 HTML 错误页(如 413 Payload Too Large)
|
||
// 必须包 try-catch,否则 JSON.parse 招错后 Promise 永远不 settle,mask loading 永不关闭
|
||
try {
|
||
result = JSON.parse(res.data)
|
||
} catch (e) {
|
||
toast('上传失败:服务器响应非 JSON 格式(可能文件过大)')
|
||
reject('上传失败:响应解析失败')
|
||
return
|
||
}
|
||
const code = result.code || 200
|
||
// @ts-ignore
|
||
const msg = errorCode[code] || result.msg || errorCode['default']
|
||
if (code === 200) {
|
||
resolve(result)
|
||
} else if (code == 401) {
|
||
showConfirm("登录状态已过期,您可以继续留在该页面,或者重新登录?").then(res => {
|
||
if (res.confirm) {
|
||
userStore.logOut().then(res => {
|
||
uni.reLaunch({ url: '/pages/login' })
|
||
})
|
||
}
|
||
})
|
||
reject('无效的会话,或者会话已过期,请重新登录。')
|
||
} else if (code === 500) {
|
||
toast(msg)
|
||
reject('500')
|
||
} else if (code !== 200) {
|
||
toast(msg)
|
||
reject(code)
|
||
}
|
||
},
|
||
fail: (error: any) => {
|
||
let { message } = error
|
||
if (message == 'Network Error') {
|
||
message = '后端接口连接异常'
|
||
} else if (message.includes('timeout')) {
|
||
message = '系统接口请求超时'
|
||
} else if (message.includes('Request failed with status code')) {
|
||
message = '系统接口' + message.substr(message.length - 3) + '异常'
|
||
}
|
||
toast(message)
|
||
reject(error)
|
||
}
|
||
})
|
||
})
|
||
}
|
||
|
||
export default upload
|