flutterdartdart-htmldart-webui

How to upload a specific type of file with FileUploadInputElement in Flutter for Web


I was trying to create a simple file uploader for a project in flutter, meant to upload images on a Firebase storage bucket, but I can't find a way to select the file type.

I've read the not-so-exhaustive documentation of Dart, but I didn't find anything similar to what I'm trying to do.

  static Future<Uri> showUploadDialog(
      firebase.StorageReference filePath, String fileName) async {
    Completer completer = Completer();

    InputElement uploadInput = FileUploadInputElement();
    uploadInput.click();

    uploadInput.onChange.listen(
      (changeEvent) {
        final file = uploadInput.files.first;
        final reader = FileReader();

        reader.onLoadEnd.listen(
          (loadEndEvent) async {
            debugPrint("Selected the file to be uploaded.");

            // Here we handle the file.
            completer.complete(uploadFile(file, filePath, fileName));
          },
        );

        reader.readAsDataUrl(file);
      },
    );

    return await completer.future;
  }

My aim is to be able to see a FileUploadInputElement which doesn't allow me to upload a file different from an image file (with an image specific extension).


Solution

  • You need to set the element's accept attribute (before simulating the click on it).

    For example, in order to only accept png and jpg files, you would neet to set it as .png,.jpg:

    InputElement uploadInput = FileUploadInputElement();
    uploadInput.accept = '.png,.jpg'
    uploadInput.click();
    

    The syntax for the accept attribute is the one specified for the HTML input accept attribute: <input accept="file_extension|audio/*|video/*|image/*|media_type">

    More details can be found online, such as in w3schools: