You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
2.7 KiB
71 lines
2.7 KiB
import 'dart:io'; |
|
import 'package:dio/dio.dart'; |
|
import 'package:flutter/foundation.dart'; // 引入 kDebugMode 和 debugPrint |
|
import 'package:get/get.dart' hide FormData, MultipartFile; |
|
import 'package:path/path.dart' as p; |
|
import 'package:problem_check_system/data/providers/http_provider.dart'; |
|
|
|
class FileRepository { |
|
final HttpProvider _httpProvider = Get.find<HttpProvider>(); |
|
|
|
/// 上传图片文件到服务器。 |
|
/// @param imageFile 要上传的本地图片文件。 |
|
/// @param cancelToken 用于取消上传任务的令牌。 |
|
/// @param onSendProgress 上传进度回调,提供已发送和总大小。 |
|
/// @return 上传成功后服务器返回的图片 URL。 |
|
Future<String> uploadImage( |
|
File imageFile, { |
|
required CancelToken cancelToken, |
|
ProgressCallback? onSendProgress, |
|
}) async { |
|
try { |
|
// 1. 创建 FormData 对象,用于构建 multipart/form-data 请求体 |
|
final formData = FormData.fromMap({ |
|
// 'file': 这通常是后端接口定义的文件字段名 |
|
'file': await MultipartFile.fromFile( |
|
imageFile.path, |
|
filename: p.basename(imageFile.path), |
|
), |
|
}); |
|
|
|
// 2. 使用 HttpProvider 的 post 方法发送请求 |
|
final response = await _httpProvider.post( |
|
'/api/Objects/association/problem', |
|
data: formData, |
|
cancelToken: cancelToken, // 将取消令牌传递给 post 请求 |
|
onSendProgress: onSendProgress, // 将进度回调传递给 post 请求 |
|
); |
|
|
|
// --- 在这里打印服务器的完整响应结构 (仅在调试模式下) --- |
|
if (kDebugMode) { |
|
debugPrint('服务器返回的状态码: ${response.statusCode}'); |
|
debugPrint('服务器返回的原始数据: ${response.data}'); |
|
} |
|
|
|
// 3. 处理响应,并返回图片 URL |
|
if (response.statusCode == 200) { |
|
final Map<String, dynamic> data = response.data; |
|
|
|
// 假设服务器返回的图片 URL 字段名为 'url' |
|
final imageUrl = data['url']; |
|
|
|
if (imageUrl is String && imageUrl.isNotEmpty) { |
|
return imageUrl; |
|
} else { |
|
// 如果返回结构不符合预期,抛出自定义异常 |
|
throw Exception('服务器响应中未找到有效的图片URL'); |
|
} |
|
} else { |
|
// 对于非 200 状态码,抛出异常 |
|
throw Exception('上传失败,状态码: ${response.statusCode}'); |
|
} |
|
} on DioException catch (e) { |
|
// 捕获 Dio 异常并重新抛出,以便上层逻辑可以处理(如取消、超时等) |
|
// 使用 rethrow 来保留原始的异常栈信息 |
|
rethrow; |
|
} catch (e) { |
|
// 捕获其他未知错误 |
|
throw Exception('图片上传发生未知错误: $e'); |
|
} |
|
} |
|
}
|
|
|