dart - Flutter:如何获取 http 请求的上传/下载进度

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

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

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 获得该上传的进度?

最佳答案

屏幕截图(Null Safe):


这个解决方案

  1. 从服务器下载图像。
  2. 显示下载进度。
  3. 下载后,图片会保存到设备存储中。

代码:

import 'package:http/http.dart' as http;

class _MyPageState extends State<MyPage> {
  int _total = 0, _received = 0;
  late http.StreamedResponse _response;
  File? _image;
  final List<int> _bytes = [];

  Future<void> _downloadImage() async {
    _response = await http.Client()
        .send(http.Request('GET', Uri.parse('https://upload.wikimedia.org/wikipedia/commons/f/ff/Pizigani_1367_Chart_10MB.jpg')));
    _total = _response.contentLength ?? 0;

    _response.stream.listen((value) {
      setState(() {
        _bytes.addAll(value);
        _received += value.length;
      });
    }).onDone(() async {
      final file = File('${(await getApplicationDocumentsDirectory()).path}/image.png');
      await file.writeAsBytes(_bytes);
      setState(() {
        _image = file;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton.extended(
        label: Text('${_received ~/ 1024}/${_total ~/ 1024} KB'),
        icon: Icon(Icons.file_download),
        onPressed: _downloadImage,
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Center(
          child: SizedBox.fromSize(
            size: Size(400, 300),
            child: _image == null ? Placeholder() : Image.file(_image!, fit: BoxFit.fill),
          ),
        ),
      ),
    );
  }
}

https://stackoverflow.com/questions/50455131/

相关文章:

flutter - 构造函数中的 Key 参数是什么

java - Flutter 无法从 url 加载图片

javascript - Flutter 是否使用 Javascript 引擎之类的东西,例如 Re

dart - 在 Flutter 中保持响应的同时制作持久的背景图像

dart - 如何为屏幕设置不同的主题?

dart - flutter 列不展开

ios - flutter : Not Connecting to IOS Simulator in

mobile - Dart:流与 ValueNotifiers

c# - 将 Flutter 前端与 Android 和 iOS 的 .NET Core 后端相结合

flutter - 如何在 flutter 的文本小部件中显示图标?