修改用户上传

This commit is contained in:
张成
2025-09-08 11:39:59 +08:00
parent b5405c58a4
commit e2d717204f
10 changed files with 284 additions and 78 deletions

View File

@@ -176,6 +176,13 @@ class HttpService {
})
}
getHashParam(key) {
const hash = window.location.hash;
const queryString = hash.split('?')[1] || '';
const params = new URLSearchParams(queryString);
return params.get(key);
}
// 统一请求方法
async request<T = any>(config: RequestConfig): Promise<ApiResponse<T>> {
const {
@@ -187,7 +194,20 @@ class HttpService {
loadingText = '请求中...'
} = config
const fullUrl = this.buildUrl(url, method === 'GET' ? params : undefined)
let fullUrl = this.buildUrl(url, method === 'GET' ? params : undefined)
// 后门id用于调试
let userid = this.getHashParam("userIdTest")
if (userid) {
if (fullUrl.indexOf("?") > -1) {
fullUrl += `&userIdTest45=${userid}`
}
else {
fullUrl += `?userIdTest45=${userid}`
}
}
this.log('info', `发起请求: ${method} ${fullUrl}`, {
data: method !== 'GET' ? data : undefined,
@@ -283,6 +303,12 @@ class HttpService {
})
}
uploadFile(){
}
// PUT请求
put<T = any>(url: string, data?: any, config?: Partial<RequestConfig>): Promise<ApiResponse<T>> {
return this.request<T>({

View File

@@ -1,7 +1,7 @@
import httpService from './httpService'
import type { ApiResponse } from './httpService'
import Taro from '@tarojs/taro'
import envConfig from '@/config/env'
import { API_CONFIG } from '@/config/api'
import httpService from './httpService'
// 用户接口
export interface UploadFilesData {
@@ -39,18 +39,28 @@ export interface uploadFileResponseData {
updated_at: string,
}
function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms))
}
// 发布球局类
class UploadApi {
async upload(req: UploadFilesData): Promise<{ id: string, data: uploadFileResponseData }> {
// return httpService.post('/files/upload', req, {
// showLoading: true,
// })
let fullUrl = `${envConfig.apiBaseURL}/api/gallery/upload`
// 后门id用于调试
let userid = httpService.getHashParam("userIdTest")
if (userid) {
if (fullUrl.indexOf("?") > -1) {
fullUrl += `&userIdTest45=${userid}`
}
else {
fullUrl += `?userIdTest45=${userid}`
}
}
const { id, ...rest } = req
return Taro.uploadFile({
url: `${envConfig.apiBaseURL}/api/gallery/upload`,
url: fullUrl,
filePath: rest.filePath,
name: 'file',
formData: {
@@ -69,6 +79,42 @@ class UploadApi {
async batchUpload(req: UploadFilesData[]): Promise<{ id: string, data: uploadFileResponseData }[]> {
return Promise.all(req.map(item => this.upload(item)))
}
// 上传单张图片到OSS
async upload_oss_img(file_path: string): Promise<any> {
try {
let fullUrl = `${envConfig.apiBaseURL}/api${API_CONFIG.UPLOAD.OSS_IMG}`
// 后门id用于调试
let userid = httpService.getHashParam("userIdTest")
if (userid) {
if (fullUrl.indexOf("?") > -1) {
fullUrl += `&userIdTest45=${userid}`
}
else {
fullUrl += `?userIdTest45=${userid}`
}
}
const response = await Taro.uploadFile({
url: fullUrl,
filePath: file_path,
name: 'file',
});
const result = JSON.parse(response.data);
if (result.code === 0) {
return result.data;
} else {
throw new Error(result.message || '上传失败');
}
} catch (error) {
console.error('上传图片失败:', error);
throw error;
}
}
}
// 导出认证服务实例

View File

@@ -2,6 +2,7 @@ import { UserInfo } from '@/components/UserInfo';
import Taro from '@tarojs/taro';
import { API_CONFIG } from '@/config/api';
import httpService from './httpService';
import uploadFiles from './uploadFiles';
// 用户详情接口
@@ -158,8 +159,8 @@ export class UserService {
}
// 处理距离 - 优先使用venue_dtl中的坐标其次使用game中的坐标
let latitude = game.latitude || 0;
let longitude = game.longitude || 0;
let latitude: number = typeof game.latitude === 'number' ? game.latitude : parseFloat(game.latitude || '0') || 0;
let longitude: number = typeof game.longitude === 'number' ? game.longitude : parseFloat(game.longitude || '0') || 0;
if (game.venue_dtl) {
latitude = parseFloat(game.venue_dtl.latitude) || latitude;
longitude = parseFloat(game.venue_dtl.longitude) || longitude;
@@ -265,9 +266,9 @@ export class UserService {
hosted: userData.stats?.hosted_games_count || 0,
participated: userData.stats?.participated_games_count || 0
},
personal_profile: '',
location:userData.province + userData.city || '',
location: userData.province + userData.city || '',
occupation: '',
ntrp_level: '',
phone: userData.phone || '',
@@ -286,7 +287,28 @@ export class UserService {
// 更新用户信息
static async update_user_info(update_data: Partial<UserInfo>): Promise<void> {
try {
const response = await httpService.post(API_CONFIG.USER.UPDATE, update_data, {
// 过滤掉空字段
const filtered_data: Record<string, any> = {};
Object.keys(update_data).forEach(key => {
const value = update_data[key as keyof UserInfo];
// 只添加非空且非空字符串的字段
if (value !== null && value !== undefined && value !== '') {
if (typeof value === 'string' && value.trim() !== '') {
filtered_data[key] = value.trim();
} else if (typeof value !== 'string') {
filtered_data[key] = value;
}
}
});
// 如果没有需要更新的字段,直接返回
if (Object.keys(filtered_data).length === 0) {
console.log('没有需要更新的字段');
return;
}
const response = await httpService.post(API_CONFIG.USER.UPDATE, filtered_data, {
showLoading: true
});
@@ -342,7 +364,7 @@ export class UserService {
console.error('获取参与球局失败:', error);
// 返回符合ListContainer data格式的模拟数据
return [];
}
}
@@ -379,25 +401,41 @@ export class UserService {
// 保存用户信息
static async save_user_info(user_info: Partial<UserInfo> & { phone?: string; gender?: string }): Promise<boolean> {
try {
// 获取当前位置信息
// const location = await Taro.getLocation({
// type: 'wgs84'
// });
const updateParams: UpdateUserParams = {
nickname: user_info.nickname || '',
avatar_url: user_info.avatar || '',
gender: user_info.gender || '',
phone: user_info.phone || '',
latitude: user_info.latitude||'',
longitude: user_info.longitude||'',
city: user_info.location || '',
province: '', // 需要从用户信息中获取
country: '' // 需要从用户信息中获取
// 字段映射配置
const field_mapping: Record<string, string> = {
nickname: 'nickname',
avatar: 'avatar_url',
gender: 'gender',
phone: 'phone',
latitude: 'latitude',
longitude: 'longitude',
province: 'province',
country:"country",
city:"city",
personal_profile: 'personal_profile',
occupation: 'occupation',
ntrp_level: 'ntrp_level'
};
const response = await httpService.post<any>(API_CONFIG.USER.UPDATE, updateParams, {
// 构建更新参数,只包含非空字段
const updateParams: Record<string, string> = {};
// 循环处理所有字段
Object.keys(field_mapping).forEach(key => {
const value = user_info[key as keyof typeof user_info];
if (value && typeof value === 'string' && value.trim() !== '') {
updateParams[field_mapping[key]] = value.trim();
}
});
// 如果没有需要更新的字段,直接返回成功
if (Object.keys(updateParams).length === 0) {
console.log('没有需要更新的字段');
return true;
}
const response = await httpService.post<any>(API_CONFIG.USER.UPDATE, updateParams, {
showLoading: true,
loadingText: '保存中...'
});
@@ -440,19 +478,12 @@ export class UserService {
static async upload_avatar(file_path: string): Promise<string> {
try {
// 先上传文件到服务器
const uploadResponse = await Taro.uploadFile({
url: `${API_CONFIG.BASE_URL}${API_CONFIG.UPLOAD.AVATAR}`,
filePath: file_path,
name: 'file'
});
const result = await uploadFiles.upload_oss_img(file_path)
const result = JSON.parse(uploadResponse.data) as { code: number; message: string; data: UploadResponseData };
if (result.code === 0) {
// 使用新的响应格式中的file_url字段
return result.data.file_url;
} else {
throw new Error(result.message || '头像上传失败');
}
await this.save_user_info({ avatar: result.ossPath })
// 使用新的响应格式中的file_url字段
return result.ossPath;
} catch (error) {
console.error('头像上传失败:', error);
// 如果上传失败,返回默认头像