downloadFile method

Future<void> downloadFile(
  1. String url, {
  2. bool silent = false,
  3. bool isImage = true,
})

Implementation

Future<void> downloadFile(String url,
    {bool silent = false, bool isImage = true}) async {
  try {
    if (!silent) isLoading.value = true;
    final dio = Dio();
    final response = await dio.get<List<int>>(
      url,
      options: Options(responseType: ResponseType.bytes),
    );
    if (response.data == null) return;
    final bytes = Uint8List.fromList(response.data!);
    final uri = Uri.parse(url);
    String fileName = uri.pathSegments.isNotEmpty
        ? uri.pathSegments.last
        : url.split('/').last;

    // Ensure no illegal characters for file systems and remove query params

    fileName = fileName.split('?').first.split('&').first;

    fileName = fileName.replaceAll(RegExp(r'[\\/:*?"<>|]'), '_');

    String? savedPath;

    if (kIsWeb) {
      final base64Str = base64Encode(bytes);

      final extension = fileName.split('.').last.toLowerCase();

      String mimeType;

      if (isImage) {
        mimeType = 'image/$extension';
      } else {
        if (extension == 'pdf') {
          mimeType = 'application/pdf';
        } else if (extension == 'xls' || extension == 'xlsx') {
          mimeType = 'application/vnd.ms-excel';
        } else {
          mimeType = 'application/octet-stream';
        }
      }

      await FileUtils.convertAndSaveBase64(
        base64String: base64Str,
        fileName: '${fileName}.pdf',
      );
    } else {
      await FileUtils.saveBytes(
        bytes: bytes,
        fileName: '${fileName}.pdf',
      );
    }

    if (!silent) {
      String msg = '${isImage ? 'image' : 'file'} downloaded successfully';

      if (savedPath != null) {
        msg += ' at $savedPath';
      }

      AppUtils.showSnackBar(msg);
    }
  } catch (e) {
    debugPrint('Error downloading file: $e');

    if (!silent)
      AppUtils.showSnackBar('Error downloading file', title: 'Error');
  } finally {
    if (!silent) isLoading.value = false;
  }
}