Search code examples
flutterdartflutter-web

Converting Html.File to Uint8List in flutter


I am using Drop zone flutter package. it returns Html.File when a file is dropped inside the widget. I want to convert it to Io.File or Uint8List format in order to upload.


Solution

  • Html File can be readed with FileReader from dart:html package:

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

    Here is full demo widget:

    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;
        });
      }
    }