Open anchao-lu opened 3 years ago
Please add download and upload method to getService that using stream. So, can handle upload and or download large file size
I have to use dio now instead. So please add download method. Thanks
alternative download without any library
/// {example of use}
///
/// await apiService.download(
/// 'http://speedtest.ftp.otenet.gr/files/test10Mb.db',
/// (await getTemporaryDirectory()).path + '/dummy.db',
/// method: 'get',
/// header: {
/// HttpHeaders.acceptEncodingHeader: '*', // Disable gzip
/// HttpHeaders.acceptCharsetHeader: '*',
/// },
/// onReceiveProgress: (count, total) {
/// if (total! <= 0) return;
/// print('percentage: ${(count / total * 100).toStringAsFixed(0)}%');
/// },
/// );
Future<dynamic> download<T>(
String url,
String savePath, {
String method = 'get',
void Function(int, int?)? onReceiveProgress,
Map<String, dynamic>? header,
}) async {
final httpClient = HttpClient();
print('${method.toUpperCase()} : $url');
if (header != null) print('${jsonEncode(header)}');
try {
// url & method
HttpClientRequest request;
switch (method.toLowerCase()) {
case 'get':
request = await httpClient.getUrl(Uri.parse(url));
break;
case 'post':
request = await httpClient.postUrl(Uri.parse(url));
break;
default:
request = await httpClient.getUrl(Uri.parse(url));
break;
}
/// header
header?.forEach((key, value) => request.headers.add(key, value));
// onReceiveProgress
final response = await request.close();
final bytes = await consolidateHttpClientResponseBytes(
response,
onBytesReceived: onReceiveProgress ??
(cumulative, total) {
if (total != null && total <= 0) return;
print('downloading: ${(cumulative / total! * 100).toStringAsFixed(0)}%');
},
);
// savePath
final file = File('$savePath');
await file.writeAsBytes(bytes);
print('file downloaded on: ${file.path}');
return '${file.path}';
} catch (error) {
throw Exception('$error');
}
}
I'm simply using an alternative solution with url launcher to download files, very simple and quick to implement
if (await launchUrl(Uri.parse(downloadUrl),
mode: LaunchMode.externalApplication)) {
} else {
...
}
GetConnect download???