uploadPhotoToServer static method
上传照片到专用接口(新方法,推荐使用) photoType: 'profile' (身形分析) | 'tryon' (虚拟试衣) | 'general' (通用)
Implementation
static Future<PhotoUploadResponse> uploadPhotoToServer({
required Uint8List imageBytes,
required String photoType,
String filename = 'photo.jpg',
}) async {
final url = '$baseUrl$uploadPhotoPath';
print('📤 上传照片到服务器: $url (type: $photoType)');
try {
// 方式2:使用 JSON Base64(更简单)
final base64Image = await compressImage(imageBytes);
// 添加 data:image/ 前缀(API 要求的格式)
final imageWithPrefix = 'data:image/png;base64,$base64Image';
print('📦 图片数据长度: ${imageWithPrefix.length} 字符');
final language = _getLanguageCode();
print('🌐 请求语言: $language');
final response = await http.post(
Uri.parse(url),
headers: {
'Content-Type': 'application/json',
'x-language': language,
},
body: json.encode({
'image': imageWithPrefix,
'type': photoType,
'filename': filename,
}),
).timeout(
const Duration(seconds: 120), // 2分钟超时
onTimeout: () {
throw Exception('上传超时:服务器响应时间过长(2分钟)');
},
);
print('✅ 上传响应状态码: ${response.statusCode}');
if (response.statusCode == 200) {
final responseBody = utf8.decode(response.bodyBytes);
print('📥 上传响应: $responseBody');
final jsonData = json.decode(responseBody);
return PhotoUploadResponse.fromJson(jsonData);
} else {
print('❌ 上传失败: ${response.body}');
throw Exception('HTTP ${response.statusCode}: ${response.body}');
}
} catch (e) {
print('❌ 照片上传失败: $e');
rethrow;
}
}