download<T> method

Future download<T>(
  1. String url,
  2. String savePath, {
  3. String method = 'get',
  4. void onReceiveProgress(
    1. int,
    2. int?
    )?,
  5. Map<String, dynamic>? header,
})

template exhttp.download

await api.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)}%'); }, );

Implementation

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 ApiException('$error');
  }
}