uploadFile static method
上传文件到服务器(通用上传,保留兼容性)
返回 UploadResponse 包含上传后的文件信息 抛出 UploadException 当上传失败时
Implementation
@Deprecated('请使用 uploadPhoto 方法')
static Future<UploadResponse> uploadFile(File file) async {
print('📤 开始上传文件: ${file.path}');
print('🔗 上传地址: $uploadUrl');
try {
// 检查文件是否存在
if (!await file.exists()) {
throw UploadException('文件不存在', code: 'FILE_NOT_FOUND');
}
// 获取文件大小
final fileSize = await file.length();
print('📦 文件大小: ${(fileSize / 1024).toStringAsFixed(2)} KB');
var request = http.MultipartRequest('POST', Uri.parse(uploadUrl));
// 添加请求头
request.headers.addAll({
'User-Agent': 'FlightBookingApp/1.0.0',
'Accept': 'application/json',
'Connection': 'keep-alive',
});
// 获取文件扩展名并确定 MIME type
final extension = file.path.toLowerCase().split('.').last;
final mimeType = _getMimeType(extension);
print('📄 文件扩展名: $extension, MIME类型: $mimeType');
// 添加文件(显式指定 contentType)
request.files.add(
await http.MultipartFile.fromPath(
'file',
file.path,
contentType: MediaType.parse(mimeType),
),
);
// 发送请求(带超时)
final streamedResponse = await request.send().timeout(
Duration(seconds: EnvironmentConfig.apiTimeout),
onTimeout: () {
throw UploadException(
'上传超时,请检查网络连接后重试',
code: 'TIMEOUT',
);
},
);
final response = await http.Response.fromStream(streamedResponse);
print('✅ 收到响应: ${response.statusCode}');
// 处理成功响应
if (response.statusCode == 200) {
try {
final jsonData = json.decode(response.body);
if (jsonData['success'] == true && jsonData['data'] != null) {
print('✅ 上传成功: ${jsonData['data']['publicUrl']}');
return UploadResponse.fromJson(jsonData['data']);
} else {
final errorMsg = jsonData['message'] ?? '上传失败';
throw UploadException(errorMsg, code: 'SERVER_ERROR');
}
} catch (e) {
if (e is UploadException) rethrow;
throw UploadException(
'服务器响应格式错误',
code: 'INVALID_RESPONSE',
details: e.toString(),
);
}
}
// 处理各种错误状态码
throw _handleErrorResponse(response);
} on SocketException {
throw UploadException(
'网络连接失败,请检查网络设置',
code: 'NETWORK_ERROR',
);
} on HttpException catch (e) {
throw UploadException(
'网络请求异常:${e.message}',
code: 'HTTP_ERROR',
);
} on UploadException {
rethrow;
} catch (e) {
print('❌ 上传异常: $e');
throw UploadException(
'上传失败:$e',
code: 'UNKNOWN_ERROR',
details: e.toString(),
);
}
}