简体   繁体   English

如何在 Flutter for Web 中使用 FileUploadInputElement 上传特定类型的文件

[英]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.我试图为 Flutter 中的项目创建一个简单的文件上传器,旨在将图像上传到 Firebase 存储桶,但我找不到选择文件类型的方法。

I've read the not-so-exhaustive documentation of Dart , but I didn't find anything similar to what I'm trying to do.我已经阅读了Dart不那么详尽的文档,但我没有找到与我想要做的类似的东西。

  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).我的目标是能够看到一个 FileUploadInputElement,它不允许我上传与图像文件不同的文件(具有图像特定的扩展名)。

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 :例如,为了只接受 png 和 jpg 文件,您需要将其设置为.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">接受属性的语法是为 HTML 输入接受属性指定的语法: <input accept="file_extension|audio/*|video/*|image/*|media_type">

More details can be found online, such as in w3schools :可以在网上找到更多详细信息,例如在w3schools 中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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