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.
64 lines
2.5 KiB
64 lines
2.5 KiB
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/core/extensions/http_response_extension.dart'; |
|
import 'package:problem_check_system/core/utils/constants/api_endpoints.dart'; |
|
import 'package:problem_check_system/data/providers/http_provider.dart'; |
|
|
|
class FileRepository { |
|
final HttpProvider _httpProvider = Get.find<HttpProvider>(); |
|
|
|
/// @param imageFilePath 要上传的本地图片文件。 |
|
/// @param cancelToken 用于取消上传任务的令牌。 |
|
/// @param onSendProgress 上传进度回调,提供已发送和总大小。 |
|
/// @return 上传成功后服务器返回的图片 URL。 |
|
Future<String> uploadImage( |
|
String imageFilePath, { |
|
required CancelToken cancelToken, |
|
ProgressCallback? onSendProgress, |
|
}) async { |
|
try { |
|
// 1. 创建 FormData 对象,用于构建 multipart/form-data 请求体 |
|
final formData = FormData.fromMap({ |
|
// 'file': 这通常是后端接口定义的文件字段名 |
|
'file': await MultipartFile.fromFile( |
|
imageFilePath, |
|
filename: p.basename(imageFilePath), |
|
), |
|
}); |
|
|
|
// 2. 使用 HttpProvider 的 post 方法发送请求 |
|
final response = await _httpProvider.post( |
|
ApiEndpoints.postUploadFile, |
|
data: formData, |
|
cancelToken: cancelToken, // 将取消令牌传递给 post 请求 |
|
onSendProgress: onSendProgress, // 将进度回调传递给 post 请求 |
|
); |
|
|
|
// --- 在这里打印服务器的完整响应结构 (仅在调试模式下) --- |
|
if (kDebugMode) { |
|
debugPrint('服务器返回的状态码: ${response.statusCode}'); |
|
debugPrint('服务器返回的原始数据: ${response.data}'); |
|
} |
|
|
|
// 3. 处理响应,并返回图片 URL |
|
if (response.isSuccess) { |
|
final Map<String, dynamic> data = response.data; |
|
|
|
// 假设服务器返回的图片 URL 字段名为 'url' |
|
String imageUrl = data['fileName']; |
|
|
|
return imageUrl; |
|
} else { |
|
throw Exception('上传失败,状态码: ${response.statusCode}'); |
|
} |
|
} on DioException catch (e) { |
|
Get.log('图片上传发生未知错误: $e'); |
|
throw Exception('图片上传失败: ${e.message}'); |
|
} catch (e) { |
|
Get.log('图片上传发生未知错误: $e'); |
|
throw Exception('图片上传发生未知错误: $e'); |
|
} |
|
} |
|
}
|
|
|