本文介绍了Flutter:如何获取 http 请求的上传/下载进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个将图像上传到服务器的应用程序,而不是仅仅显示一个微调器,我希望能够获得上传状态的进度.

I am writing an app that uploads an image to a server, and instead of just showing a spinner, I'd love to be able to get progress on the status of that upload.

此外,我想在不使用 Multipart 表单数据的情况下执行此操作.这是我目前正在使用的代码 - 但它似乎因管道损坏而停滞不前,而且我对数据是否正在发送到服务器的反馈为零:

Additionally, I want to do this without using Multipart form data. This is the code I'm currently using - but it appears to be stalling out with a broken pipe, and I have zero feedback as to whether data is being sent to the server:

Future<String> _uploadFile(File assetFile) async {
  final url = <removed>;

  final stream = await assetFile.openRead();
  int length = assetFile.lengthSync();

  final client = new HttpClient();

  final request = await client.postUrl(Uri.parse(url));
request.headers.add(HttpHeaders.CONTENT_TYPE,  "application/octet-stream");
  request.contentLength = length;

  await request.addStream(stream);
  final response = await request.close();
  // response prociessing.
}

是否可以将大数据作为流发送而不将其读入内存,我可以使用当前的 dart/flutter API 获取上传进度吗?

Is it possible to send large data as a stream without reading it into memory, and can I get progress on that upload with current dart / flutter APIs?

推荐答案

您已经在使用 Stream 的方式意味着您没有将整个文件读入内存.它可能被读取为 64k 块.

The way that you are already using Stream means that you are not reading the whole file into memory. It's being read in as, probably, 64k chunks.

您可以使用 StreamTransformer 拦截生产者 (File) 和消费者 (HttpClient) 之间的流,如下所示:

You could intercept the stream between the producer (File) and consumer (HttpClient) with a StreamTransformer, like this:

  int byteCount = 0;
  Stream<List<int>> stream2 = stream.transform(
    new StreamTransformer.fromHandlers(
      handleData: (data, sink) {
        byteCount += data.length;
        print(byteCount);
        sink.add(data);
      },
      handleError: (error, stack, sink) {},
      handleDone: (sink) {
        sink.close();
      },
    ),
  );
....
  await request.addStream(stream2);

您应该看到 byteCount 以 64k 块为单位递增.

You should see byteCount incrementing in 64k chunks.

这篇关于Flutter:如何获取 http 请求的上传/下载进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 14:08