jonataslaw / getx

Open screens/snackbars/dialogs/bottomSheets without context, manage states and inject dependencies easily with Get.
MIT License
10.39k stars 1.63k forks source link

GetConnect download??? #1464

Open anchao-lu opened 3 years ago

anchao-lu commented 3 years ago

GetConnect download???

inyong1 commented 3 years ago

Please add download and upload method to getService that using stream. So, can handle upload and or download large file size

myemuk commented 3 years ago

I have to use dio now instead. So please add download method. Thanks

2lineofcode commented 1 year ago

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');
    }
  }
kauemurakami commented 2 months ago

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 {
            ...
          }