Flutter Web Image Picker仅获取图像文件

时间:2019-12-24 04:26:48

标签: flutter flutter-web

我正试图从颤动的网络中获取图像,现在我正在这样做

try {
  final html.InputElement input = html.document.createElement('input');
  input
    ..type = 'file'
    ..accept = 'image/*';

  input.onChange.listen((e) {
    if (input.files.isEmpty) return;
    final reader = html.FileReader();
    reader.readAsDataUrl(input.files[0]);
    reader.onError.listen((err) => setState(() {
          print(err.toString());
        }));
    reader.onLoad.first.then((res) {
      final encoded = reader.result as String;
      // remove data:image/*;base64 preambule
      final stripped =
          encoded.replaceFirst(RegExp(r'data:image/[^;]+;base64,'), '');

      setState(() {
        backgroundBytes = base64.decode(stripped);
        backgroundImage = input.files[0];
        metaDataBackground = input.files[0].type;
      });
    });
  });

  input.click();
} catch (e) {
  print('Error background image');
}

它工作得很好,但是用户可以将允许的文件类型更改为所有文件,而且我必须阻止该操作

Bloack acction picker

有什么办法吗?

1 个答案:

答案 0 :(得分:0)

您不能阻止该操作,请参见参考文献Limit file format when using <input type="file">?
使用accept属性仅提供一种过滤感兴趣类型的文件的方法。浏览器仍然允许用户选择任何类型的文件。

input.onChange.listen中,您可以检查file extension typealert警告用户他没有选择正确的类型