Flutter:如何获取http请求的上传/下载进度 [英] Flutter: How to get upload / download progress for http requests

查看:600
本文介绍了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拦截生产者(文件)和消费者(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请求的上传/下载进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆