skip to Main Content

I need to convert a local HTML file to a Uint8list so it could be printed. Solutions I’ve found don’t seem to work.

I tried using readAsArrayBuffer but it did not work for me.

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

the code above requires a Html.file object, I couldn’t create one.

2

Answers


  1. You may use the file_picker package for opening local files.

    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['html'],
    );
    
    if (result != null) {
      Uint8List fileBytes = result.files.first.bytes;
      String fileName = result.files.first.name;
    } else {
      // User canceled the picker
    }
    
    Login or Signup to reply.
  2. If you want to read a local HTML file in Dart outside of a web environment , you can use the dart:io library for file I/O.

    //Replace 'path/to/your/file.html' with the actual path to your HTML file
    String filePath = 'path/to/your/file.html';
    
    
    // Read the HTML file as a byte list
    Future<Uint8List?> readHtmlFile(String filePath) async {
    try {
      final File file = File(filePath);
      final Uint8List byteList = await file.readAsBytes();
      return byteList;
    } catch (e) {
      print('Error reading HTML file: $e');
      return null;
     }
    }
    
    // Usage
    readHtmlFile(filePath).then((Uint8List? byteList) {
    if (byteList != null) {
      // Do something with the Uint8List
      print('Successfully loaded HTML file as Uint8List: $byteList');
     } else {
      print('Failed to load HTML file.');
     }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search