chunkedUpload method
Future<Response>
chunkedUpload({
- required String path,
- required Map<
String, dynamic> params, - required String paramName,
- required String idParamName,
- required Map<
String, String> headers, - dynamic onProgress()?,
override
Upload a file in chunks.
Implementation
@override
Future<Response> chunkedUpload({
required String path,
required Map<String, dynamic> params,
required String paramName,
required String idParamName,
required Map<String, String> headers,
Function(UploadProgress)? onProgress,
}) async {
InputFile file = params[paramName];
if (file.bytes == null) {
throw AppwriteException("File bytes must be provided for Flutter web");
}
int size = file.bytes!.length;
late Response res;
if (size <= CHUNK_SIZE) {
params[paramName] = http.MultipartFile.fromBytes(paramName, file.bytes!,
filename: file.filename);
return call(
HttpMethod.post,
path: path,
params: params,
headers: headers,
);
}
var offset = 0;
if (idParamName.isNotEmpty && params[idParamName] != 'unique()') {
//make a request to check if a file already exists
try {
res = await call(
HttpMethod.get,
path: path + '/' + params[idParamName],
headers: headers,
);
final int chunksUploaded = res.data['chunksUploaded'] as int;
offset = chunksUploaded * CHUNK_SIZE;
} on AppwriteException catch (_) {}
}
while (offset < size) {
var chunk;
final end = min(offset + CHUNK_SIZE, size);
chunk = file.bytes!.getRange(offset, end).toList();
params[paramName] = http.MultipartFile.fromBytes(paramName, chunk,
filename: file.filename);
headers['content-range'] =
'bytes $offset-${min<int>((offset + CHUNK_SIZE - 1), size - 1)}/$size';
res = await call(HttpMethod.post,
path: path, headers: headers, params: params);
offset += CHUNK_SIZE;
if (offset < size) {
headers['x-appwrite-id'] = res.data['\$id'];
}
final progress = UploadProgress(
$id: res.data['\$id'] ?? '',
progress: min(offset, size) / size * 100,
sizeUploaded: min(offset, size),
chunksTotal: res.data['chunksTotal'] ?? 0,
chunksUploaded: res.data['chunksUploaded'] ?? 0,
);
onProgress?.call(progress);
}
return res;
}