【问题标题】:Converting Html.File to Uint8List in flutter在颤动中将 Html.File 转换为 Uint8List
【发布时间】:2021-12-01 23:14:17
【问题描述】:

我正在使用Drop zone 颤振包。当文件被放入小部件时,它会返回 Html.File。我想将其转换为 Io.File 或 Uint8List 格式以便上传。

【问题讨论】:

    标签: flutter dart flutter-web


    【解决方案1】:

    Html 文件 可以用FileReader 读取 来自 dart:html 包:

      void loadImage(html.File file) async {
        final reader = html.FileReader();
        reader.readAsArrayBuffer(file);
        await reader.onLoad.first;
        setState(() {
          imageData = reader.result as Uint8List;
        });
      }
    

    这是完整的演示小部件:

    import 'dart:typed_data';
    import 'dart:html' as html;
    
    import 'package:flutter/material.dart';
    import 'package:drop_zone/drop_zone.dart';
    
    class DropzoneDemo extends StatefulWidget {
      @override
      _DropzoneDemoState createState() => _DropzoneDemoState();
    }
    
    class _DropzoneDemoState extends State<DropzoneDemo> {
      Uint8List? imageData;
    
      @override
      Widget build(BuildContext context) => MaterialApp(
            home: Scaffold(
              appBar: AppBar(
                title: const Text('Dropzone demo'),
              ),
              body: Center(
                child: Container(
                  child: Stack(
                    children: [
                      DropZone(
                        onDrop: (List<html.File>? files) => loadImage(files![0]),
                        child: Container(),
                      ),
                      if (imageData != null)
                        Center(child: Image.memory(imageData!))
                      else
                        Center(child: Text('Drop image here')),
                    ],
                  ),
                ),
              ),
            ),
          );
    
      void loadImage(html.File file) async {
        final reader = html.FileReader();
        reader.readAsArrayBuffer(file);
        final res = await reader.onLoad.first;
        print('${res.total} bytes loaded');
        setState(() {
          imageData = reader.result as Uint8List;
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 2020-05-20
      • 2022-10-05
      • 2020-06-15
      • 2019-05-30
      • 2022-08-18
      • 2021-09-19
      • 2020-08-25
      • 2020-07-25
      相关资源
      最近更新 更多