// 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