简体   繁体   中英

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).

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 :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM