downloadUri method

Future<Response> downloadUri({
  1. ProgressCallback? onReceiveProgress,
})

Implementation

Future<Response> downloadUri({ProgressCallback? onReceiveProgress}) async {
  // final Directory tempDir = await getTemporaryDirectory();

  // 检查文件是否存在,获取已下载的字节数
  int start = 0;
  final File file = File(savePath);
  if (await file.exists()) {
    start = await file.length();
  }

  return DioManager().dio.downloadUri(
    path,
    savePath,
    onReceiveProgress: ((count, total) {
      if (total != -1) {
        print((count / total * 100).toStringAsFixed(0) + "%");
      }
    }),
    options: this.opt?.copyWith(
      responseType: ResponseType.stream,
      headers: {
        HttpHeaders.rangeHeader: 'bytes=$start-', // 请求下载剩余部分
      },
    ),
  ).then((response) {
    var raf = file.openSync(mode: FileMode.writeOnlyAppend);
    response.data!.stream.listen(
      (List<int> chunk) {
        raf.writeFromSync(chunk);
      },
      onDone: () {
        raf.closeSync();
        print('Download complete');
      },
      onError: (error) {
        print('Download error: $error');
      },
    );
    return response;
  });
}