upload_file.dart
9.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import 'dart:io';
import 'package:appframe/config/constant.dart';
import 'package:appframe/services/api_service.dart';
import 'package:appframe/services/dispatcher.dart';
import 'package:appframe/utils/file_type_util.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as path;
import 'package:uuid/uuid.dart';
class UploadFileHandler extends MessageHandler {
@override
Future handleMessage(params) async {
if (params is! Map<String, dynamic>) {
throw Exception('参数错误');
}
final String? tempFilePath = params['tempFilePath'] as String?;
if (tempFilePath == null || tempFilePath.isEmpty) {
throw Exception('参数错误');
}
final String? busi = params['busi'] as String?;
if (busi == null || busi.isEmpty) {
throw Exception('参数错误');
}
final String? subBusi = params['subBusi'] as String?;
if (subBusi == null || subBusi.isEmpty) {
throw Exception('参数错误');
}
final result = await compute(_handleUpload, {'filePath': tempFilePath, 'busi': busi, 'subBusi': subBusi});
// final result = await _handleUpload({'filePath': tempFilePath});
return result;
}
static const _bxeBaseUrl = 'https://iotapp-dev.banxiaoer.com/iotapp';
static const _signatureNewUrl = '/api/v1/obs/multipart/signaturenew';
static const _signatureNextUrl = '/api/v1/obs/multipart/signaturenext';
static const _completeUrl = '/api/v1/obs/multipart/complete';
/// 在Isolate中执行
static Future<Map<String, dynamic>> _handleUpload(Map<String, dynamic> fileParams) async {
String filePath = fileParams['filePath'] as String;
String busi = fileParams['busi'] as String;
String subBusi = fileParams['subBusi'] as String;
print('参数-------');
print('filePath:$filePath ');
print('busi:$busi ');
print('subBusi:$subBusi ');
print('参数-------');
if (filePath.startsWith(Constant.localServerUrl)) {
filePath = filePath.replaceFirst(Constant.localServerUrl, '');
}
if (filePath.startsWith(Constant.localServerTemp)) {
filePath = filePath.replaceFirst(Constant.localServerTemp, '');
}
final bxeApiService = ApiService(baseUrl: _bxeBaseUrl);
// 由于服务端签名时未设置Content-Type,这里必须设置为空,否则会报签名错误
// 由于封装有默认值,所以不能不设置
final obsApiService = ApiService(defaultHeaders: {'Content-Type': '', 'Accept': ''});
String logicPrefix = _getLoginPrefix(busi, subBusi);
print('logicPrefix: $logicPrefix');
//并行上传分段
final uploadResult = await _uploadInParallel(bxeApiService, obsApiService, logicPrefix, filePath);
String objectKey = uploadResult['objectKey'] as String;
String bucket = uploadResult['bucket'] as String;
String uploadId = uploadResult['uploadId'] as String;
Map<int, String> tagsMap = uploadResult['tagsMap'] as Map<int, String>;
//请求合并文件
String location = await _merge(bxeApiService, objectKey, bucket, uploadId, tagsMap);
print('location: $location');
//关闭Dio
bxeApiService.close();
obsApiService.close();
return {'url': _addPreUrl(location)};
}
/// 并行上传
static Future<Map<String, dynamic>> _uploadInParallel(
ApiService bxeApiService,
ApiService obsApiService,
String logicPrefix,
String filePath, {
int maxConcurrency = 5,
}) async {
//判断文件
File file = File(filePath);
if (!file.existsSync()) {
throw Exception('文件不存在');
}
//暂时仅支持200M的文件上传
final fileSize = file.lengthSync();
if (fileSize > 1024 * 1024 * 200) {
throw Exception('上传的文件过大');
}
//分段大小2M
final chunkSize = Constant.obsUploadChunkSize;
//分段总数
final totalChunks = (fileSize / chunkSize).ceil();
final randomAccessFile = file.openSync();
//bucket 存储桶名称 : bxe-files | bxe-pics | bxe-videos
String bucket;
if (await FileTypeUtil.isImage(file)) {
bucket = 'bxe-pics';
} else if (await FileTypeUtil.isVideo(file)) {
bucket = 'bxe-videos';
} else {
bucket = 'bxe-files';
}
//生成唯一文件名,
// String objectKey = 'd2/test/file.csv';
var uuid = Uuid();
String objectKey = '$logicPrefix/${uuid.v4()}${path.extension(file.path)}';
print('objectKey: $objectKey');
String uploadId = '';
Map<int, String> tagsMap = {};
final futures = <Future>[];
for (int i = 0; i < totalChunks; i++) {
// 控制并发数量
if (futures.length >= maxConcurrency) {
await Future.wait(futures);
futures.clear();
}
final start = i * chunkSize;
final actualChunkSize = (i + 1) * chunkSize > fileSize ? fileSize - start : chunkSize;
final chunk = Uint8List(actualChunkSize);
randomAccessFile.setPositionSync(start);
await randomAccessFile.readInto(chunk, 0, actualChunkSize);
String chunkSignUrl;
if (i == 0) {
final initResult = await _init(bxeApiService, objectKey, bucket);
uploadId = initResult['upload_id'] as String;
chunkSignUrl = initResult['signed_url'] as String;
} else {
final nextResult = await _next(bxeApiService, objectKey, bucket, uploadId, i + 1);
chunkSignUrl = nextResult['signed_url'] as String;
}
print('chunkSignUrl: $chunkSignUrl');
// await _uploadChunkWithRetry(obsApiService, chunkSignUrl, i, chunk, tagsMap);
final future = _uploadChunkWithRetry(obsApiService, chunkSignUrl, i, chunk, tagsMap);
futures.add(future);
}
// 等待剩余的上传完成
if (futures.isNotEmpty) {
await Future.wait(futures);
}
randomAccessFile.closeSync();
return {'objectKey': objectKey, 'bucket': bucket, 'uploadId': uploadId, 'tagsMap': tagsMap};
}
/// 初始化,请求后端获取签名信息和上传任务ID
static Future<Map<String, dynamic>> _init(ApiService bxeApiService, String objectKey, String bucket) async {
var endpoint = '$_signatureNewUrl?objectKey=$objectKey&bucket=$bucket';
final resp = await bxeApiService.get(endpoint);
return resp.data;
}
/// 每次上传前,请求后端获取签名信息
static Future<Map<String, dynamic>> _next(
ApiService bxeApiService,
String objectKey,
String bucket,
String uploadId,
int partNum,
) async {
var endpoint = '$_signatureNextUrl?objectKey=$objectKey&bucket=$bucket&uploadId=$uploadId&partNum=$partNum';
final resp = await bxeApiService.get(endpoint);
return resp.data;
}
/// 上传段,按照最大重试次数进行上传重试
static Future<void> _uploadChunkWithRetry(
ApiService obsApiService,
String signUrl,
int chunkIndex,
Uint8List chunk,
Map<int, String> tagsMap, {
int maxRetries = 3,
}) async {
for (int attempt = 0; attempt <= maxRetries; attempt++) {
try {
final resp = await _uploadChunk(obsApiService, signUrl, chunk);
if (resp.statusCode == 200) {
final etags = resp.headers['etag'] as List<String>;
tagsMap[chunkIndex + 1] = etags[0];
return; // 上传成功
} else {
throw Exception('Chunk $chunkIndex upload failed: ${resp.statusCode}');
}
} catch (e) {
if (attempt == maxRetries) {
throw Exception('Chunk $chunkIndex upload failed after $maxRetries attempts: $e');
}
// 等待后重试
await Future.delayed(Duration(seconds: 2 * attempt));
}
}
}
/// 上传段
static Future<Response> _uploadChunk(ApiService obsApiService, String signUrl, Uint8List chunk) async {
var url = signUrl.replaceFirst('AWSAccessKeyId=', 'AccessKeyId=').replaceFirst(':443', '');
try {
Response response = await obsApiService.put(url, chunk);
return response;
} catch (e) {
print('Chunk upload failed: $e');
throw Exception('Chunk upload failed: $e');
}
}
/// 请求合并文件
static Future<String> _merge(
ApiService bxeApiService,
String objectKey,
String bucket,
String uploadId,
Map<int, String> tagsMap,
) async {
final parts = [];
for (int i = 1; i <= tagsMap.length; i++) {
parts.add({'partNumber': i, 'etag': tagsMap[i]});
}
final response = await bxeApiService.post(_completeUrl, {
'objectKey': objectKey,
'bucket': bucket,
'uploadId': uploadId,
'parts': parts,
});
if (response.statusCode != 200) {
throw Exception('合并文件失败');
}
return response.data["location"];
}
static String _getLoginPrefix(String busi, String subBusi) {
var now = DateTime.now();
var year = now.year;
var month = now.month;
var day = now.day;
return 'd2/pridel/user/$year$month$day/bxe/${busi}_$subBusi';
}
static String _addPreUrl(String location) {
// /bxe-pics/d2/pridel/user/20251017/bxe/bxe_homework/f4ea233d-9e1b-4a3f-bc8f-b64e776f42a6.jpg
if (location.startsWith('/bxe-files')) {
return 'https://files-obs.banxiaoer.com${location.substring(10)}';
} else if (location.startsWith('/bxe-pics')) {
return 'https://pics-obs.banxiaoer.com${location.substring(9)}';
} else if (location.startsWith('/bxe-videos')) {
return 'https://videos-obs.banxiaoer.com${location.substring(11)}';
} else {
return location;
}
}
}