Files
xingque/utils/upload.js

95 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// utils/upload.js
import request from './request.js'
const app = getApp()
/**
* 统一的异步上传方法
* @param {object} options 配置项
* @returns {Promise} Promise对象
*/
const upload = async (options) => {
const {
url,
formData = {},
filePath = null,
fileName = 'file'
} = options
// 获取token
const token = wx.getStorageSync('token')
if (!token) {
throw new Error('未登录')
}
// 拼接完整URL
const fullUrl = `${app.globalData.apiBaseUrl}${url}`
if (filePath) {
// 有文件上传使用wx.uploadFile
return new Promise((resolve, reject) => {
// 先验证文件是否存在
wx.getFileInfo({
filePath,
success: () => {
// 文件存在,开始上传
wx.uploadFile({
url: fullUrl,
filePath,
name: fileName,
formData,
header: {
'Authorization': `Bearer ${token}`
},
success: (res) => {
if (res.statusCode === 200) {
try {
const data = JSON.parse(res.data)
resolve({
statusCode: res.statusCode,
data
})
} catch (e) {
console.error('解析JSON失败:', e, '原始数据:', res.data)
reject(new Error('解析响应数据失败'))
}
} else if (res.statusCode === 401) {
// token过期或无效
wx.removeStorageSync('token')
wx.removeStorageSync('userInfo')
reject(new Error('认证失败'))
} else {
console.error('上传失败,状态码:', res.statusCode, '响应:', res)
reject(new Error(`上传失败,状态码:${res.statusCode}`))
}
},
fail: (err) => {
console.error('wx.uploadFile失败:', err)
reject(new Error('网络请求失败'))
}
})
},
fail: (err) => {
console.error('文件不存在或无法访问:', err)
reject(new Error('文件不存在或无法访问'))
}
})
})
} else {
// 没有文件使用封装的request
// 注意这里应该使用传入的url而不是硬编码
return request({
url, // 使用传入的url
method: 'POST',
data: formData,
header: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
})
}
}
export default upload