首页 > 解决方案 > 如何在 web 中使用 file_picker 显示选取的图像?

问题描述

当文件路径在网络file_picker平台中时,如何在网络中显示图像?null

如果路径不为空,则显示图像太容易了Image.file(File)

Image.file(context.select<BlogProvider, File>((BlogProvider p) => p.image))

但它无法在网络中为图像创建文件,因为浏览器不提供文件路径并且它为空。

Future<void> pickImage() async {
    /// If [withReadStream] is set, picked files will have its byte data available as a [Stream<List<int>>]
    /// which can be useful for uploading and processing large files.
    FilePickerResult result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['jpg', 'jpeg'],
      withReadStream: true,
    );
    if (result != null) {
      PlatformFile file = result.files.single; //single means I am Picking just One file not more
      _blogImage = File(file.path);//Null in web ,but Ok in Android
      notifyListeners();
    } else {
      // User canceled the picker
    }

  }

标签: flutterflutter-web

解决方案


withReadStream设置为true时,可以通过以下方式访问所选图像:

        file.readStream.listen((event) {
          _blogImage = Image.memory(event);
          notifyListeners();
        });

但是当withReadStreamfalse时:

        _blogImage = Image.memory(file.bytes);
        notifyListeners();

尽管在web的Flutter中file.pathnull ,但file.name设置正确,我们可以显示它。

更多信息在这里

另一种方式(没有file_picker包):

  import 'dart:html' as html;
  // ...

  void pickFile() {
    final input = html.FileUploadInputElement()..accept = 'image/*';
    input.onChange.listen((event) {
      if (input.files.isNotEmpty) {
          fileName = input.files.first.name; // file name without path!
          
          // synthetic file path can be used with Image.network()
          url = html.Url.createObjectUrl(input.files.first);
        });
      }
    });
    input.click();
  }

推荐阅读