saveLinkStream static method

Future<bool> saveLinkStream({
  1. required String name,
  2. required LinkDetails link,
  3. required bool includeCredentials,
})

Implementation

static Future<bool> saveLinkStream({
  required String name,
  required LinkDetails link,
  required bool includeCredentials,
}) async {
  if (!canSaveStream) {
    throw UnsupportedError(
      'Authenticated streamed web saving requires the File System Access API. '
      'Use Chrome/Edge, or use downloadLink with a signed URL.',
    );
  }
  if (link.method.toUpperCase() != 'GET' || link.body != null) {
    throw UnsupportedError(
      'saveLinkAsStream on web supports authenticated GET downloads only.',
    );
  }

  final options = JSObject();
  options.setProperty('suggestedName'.toJS, name.toJS);

  final headers = Headers();
  link.headers?.forEach((key, value) {
    headers.set(key, value);
  });

  final response = await window
      .fetch(
        _linkWithQuery(link).toJS,
        RequestInit(
          method: link.method,
          headers: headers,
          credentials: includeCredentials ? 'include' : 'same-origin',
        ),
      )
      .toDart;

  if (!response.ok) {
    throw Exception(
      'Download failed with HTTP ${response.status} ${response.statusText}',
    );
  }

  final body = response.body;
  if (body == null) {
    throw Exception('Download response does not contain a streamable body.');
  }

  final handle = await _showSaveFilePicker(options).toDart;
  final writable = await handle.createWritable().toDart;
  try {
    await body.pipeTo(writable).toDart;
    return true;
  } catch (_) {
    await writable.abort().toDart;
    rethrow;
  }
}