80 lines
1.9 KiB
Dart
80 lines
1.9 KiB
Dart
import 'dart:typed_data';
|
|
import 'package:dio/dio.dart';
|
|
import '../utils/app_config.dart';
|
|
|
|
class ApiService {
|
|
late final Dio _dio;
|
|
|
|
ApiService() {
|
|
_dio = Dio(BaseOptions(
|
|
baseUrl: AppConfig.apiBaseUrl,
|
|
connectTimeout: const Duration(seconds: 10),
|
|
receiveTimeout: const Duration(seconds: 10),
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
));
|
|
|
|
// 添加日志拦截器
|
|
_dio.interceptors.add(LogInterceptor(
|
|
requestBody: false, // 不打印请求体(图片太大)
|
|
responseBody: true,
|
|
error: true,
|
|
));
|
|
}
|
|
|
|
/// 上传图像到后端
|
|
Future<Map<String, dynamic>> uploadImage(Uint8List imageBytes) async {
|
|
try {
|
|
final formData = FormData.fromMap({
|
|
'file': MultipartFile.fromBytes(
|
|
imageBytes,
|
|
filename: 'image_${DateTime.now().millisecondsSinceEpoch}.jpg',
|
|
),
|
|
});
|
|
|
|
final response = await _dio.post(
|
|
'/api/v1/images/upload',
|
|
data: formData,
|
|
);
|
|
|
|
return response.data;
|
|
} catch (e) {
|
|
print('上传图像失败: $e');
|
|
rethrow;
|
|
}
|
|
}
|
|
|
|
/// 请求 AI 分析
|
|
Future<Map<String, dynamic>> analyzeImage(String imageUrl) async {
|
|
try {
|
|
final response = await _dio.post(
|
|
'/api/v1/analysis/analyze',
|
|
data: {'image_url': imageUrl},
|
|
);
|
|
|
|
return response.data;
|
|
} catch (e) {
|
|
print('分析图像失败: $e');
|
|
rethrow;
|
|
}
|
|
}
|
|
|
|
/// 一步到位:上传并分析
|
|
Future<Map<String, dynamic>> uploadAndAnalyze(Uint8List imageBytes) async {
|
|
try {
|
|
// 1. 上传图像
|
|
final uploadResult = await uploadImage(imageBytes);
|
|
final imageUrl = uploadResult['url'];
|
|
|
|
// 2. 请求分析
|
|
final analysisResult = await analyzeImage(imageUrl);
|
|
|
|
return analysisResult;
|
|
} catch (e) {
|
|
print('上传并分析失败: $e');
|
|
rethrow;
|
|
}
|
|
}
|
|
}
|