簡體   English   中英

如何在flutter http、dio或flutter_downloader上調整下載緩沖區大小?

[英]How to adjust download buffer size on flutter http, dio or flutter_downloader?

在此處輸入圖像描述

我想下載一個大約300MB的大文件。 它比我想象的要慢很多,當我查看日志時,我看到它正在獲取大小約為8KB的字節。 即使我尋找其他顫振庫,我也沒有找到調整下載緩沖區大小的方法。 我該如何調整?

您可以使用ChunkedStreamReader使用自定義 chunkSize(例如 64KB)處理響應流並將其寫入文件。 另請參閱此 GitHub 問題

在下面的示例中,它將以流的形式偵聽響應,然后從 ChunkedStreamReader 讀取具有所需塊大小(64*1024 = 64KB)的字節,並將獲取的塊寫入文件。

// Download file
try {
  int offset = 0;
  var httpClient = http.Client();
  var request = http.Request('GET', Uri.parse(url));
  var response = httpClient.send(request);

  // Open file
  File file = File('$downloadPath.tmp');

  response.asStream().listen((http.StreamedResponse r) async {
    final reader = ChunkedStreamReader(r.stream);
    try {
      // Set buffer size to 64KB
      int chunkSize = 64 * 1024;
      Uint8List buffer;
      do {
        buffer = await reader.readBytes(chunkSize);
        // Add buffer to chunks list
        offset += buffer.length;
        print('Downloading $filename ${downloaded ~/ 1024 ~/ 1024}MB');
        // Write buffer to disk
        await file.writeAsBytes(buffer, mode: FileMode.append);
      } while (buffer.length == chunkSize);

      // Rename file from .tmp to non-tmp extension
      await file.rename(downloadPath);
      print('Downloaded $filename');
    } catch (e) {
      print(e);
    } finally {
      reader.cancel();
    }
  }).onDone(() async {
    // do something when finished
  });
} catch (error) {
  print('Error downloading: $error');
}

在此處輸入圖片說明

我想下載一個大約300MB的大文件。 這比我想象的要慢得多,當我查看日志時,我發現它正在獲取大小約為8KB字節。 我沒有找到一種方法來調整下載緩沖區的大小,即使我正在尋找其他Flutter庫也是如此。 我該如何調整?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM