download method

Future<void> download(
  1. Uri uri,
  2. File target, {
  3. int? size,
  4. String? sha256,
  5. Map<String, String> headers = const {},
  6. ByteProgress? onProgress,
  7. CancelToken? cancel,
  8. Duration? deadline,
})

Downloads uri into target without holding it in memory: for a file too large for get (a Flutter SDK, about 2 GB).

The bytes go to <target>.part as they come, hashed on the way. A .part left by a download cut short is resumed: only the rest is asked for (a ByteRange, when size is known), and a server that sends the whole file instead starts it over. A connection that breaks mid-way is resumed the same way, up to 3 times. Once all is there, it must be size bytes with the SHA-256 sha256 (each when given), or the part is deleted and a FetchException says why; then it is renamed to target.

onProgress counts the whole file, the resumed part included. The whole download fails once deadline passes (deadlineFor size, or 4 GiB, when null).

Implementation

Future<void> download(
  Uri uri,
  File target, {
  int? size,
  String? sha256,
  Map<String, String> headers = const {},
  ByteProgress? onProgress,
  CancelToken? cancel,
  Duration? deadline,
}) async {
  if (!isFetchAllowed(uri)) {
    throw FetchException('Downloads must use https.', uri: uri);
  }
  final part = File('${target.path}.part');
  part.parent.createSync(recursive: true);
  final allowed = deadline ?? deadlineFor(size ?? 4 << 30);
  final clock = Stopwatch()..start();
  var broken = 0;
  for (var attempt = 1; ; attempt++) {
    cancel?.check();
    final left = allowed - clock.elapsed;
    if (left <= Duration.zero) throw _late(uri, allowed);
    var have = part.existsSync() ? part.lengthSync() : 0;
    if (size != null && have > size || size == null && have > 0) {
      // Not a part of this file, or one that can't be resumed blind.
      part.deleteSync();
      have = 0;
    }
    final body = _FileBody(part, offset: have);
    if (have > 0) await body.hashExisting();
    if (size != null && have == size) break;
    final range = have > 0 ? ByteRange(have, size! - 1) : null;
    try {
      final (response, retryAfter) = await _attempt(
        uri,
        headers: range == null
            ? headers
            : {...headers, 'Range': range.header},
        onProgress: onProgress,
        cancel: cancel,
        maxBytes: size == null ? null : size - have,
        range: range,
        allowRedirect: null,
        attempt: attempt,
        left: left,
        late: () => _late(uri, allowed),
        into: body,
      );
      if (response != null) break;
      if (clock.elapsed + retryAfter! >= allowed) throw _late(uri, allowed);
      await _pause(retryAfter, cancel);
    } on FetchException catch (e) {
      if (range != null && e.statusCode == HttpStatus.ok) {
        // The server can't send a part: the whole file, from the start.
        part.deleteSync();
        continue;
      }
      if (range != null &&
          e.statusCode == HttpStatus.requestedRangeNotSatisfiable) {
        part.deleteSync();
        continue;
      }
      // A broken connection (no status): resume, a few times.
      if (e.statusCode != null || ++broken > _retries) rethrow;
    }
  }
  final got = part.lengthSync();
  if (size != null && got != size) {
    part.deleteSync();
    throw FetchException(
      'The download was $got bytes, not the $size expected.',
      uri: uri,
    );
  }
  if (sha256 != null) {
    final hash = Sha256();
    await for (final chunk in part.openRead()) {
      hash.add(chunk);
    }
    final actual = Sha256.hex(hash.close());
    if (actual != sha256.toLowerCase()) {
      part.deleteSync();
      throw FetchException(
        "The download's SHA-256 is $actual, not $sha256: it was damaged "
        'or changed on the way.',
        uri: uri,
      );
    }
  }
  if (target.existsSync()) target.deleteSync();
  retryOnLock(() => part.renameSync(target.path));
}