Search code examples
angular-dart

AngularDart upload file convert to base64 string


I am using AngularDart, Angular 5 and Dart 2. I have a file input with a change action.

<input #inp type="file" id="upload_image" accept="image/*" (change)="handleUpload($event)">

This is my handleUpload.

Future<void> handleUpload(html.Event e) async {
    e.preventDefault();
    picfile = (e.target as html.FileUploadInputElement).files[0];

}

I want to be able to take the html.File object and convert it to an io.File object so that I can base64 encode it and pass it in my JSON to my server. I do something similar in my Flutter app. Not sure what I am missing, but nothing seems to get the html.File object to be an io.File object.

Any help would be greatly appreciated.


Solution

  • import 'dart:html';
    ...
    
    var blob = e.target as html.FileUploadInputElement).files[0];
    var reader = new FileReader()..readAsArrayBuffer(blob);
    await reader.onLoadEnd.first;
    List<int> /* or Uint8List */ result = reader.result;
    print(result);
    

    Here you should be able to base64 encode (https://stackoverflow.com/a/36529793/217408)