简体   繁体   English

如何在 web 中使用 file_picker 显示选取的图像?

[英]How to show picked image with file_picker in web?

how can I show image picked by file_picker in web while the file path is null in web platform?如何在web平台中显示文件路径为nullfile_picker中的file_picker拾取的图像?

If the path was not null, showing the image is too easy with Image.file(File) :如果路径不是 null,则使用Image.file(File)显示图像太容易了:

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

but It can not create File for image in web because browsers don't give file path and It's null.但它无法为 web 中的图像创建文件,因为浏览器不提供文件路径,它是 null。

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
    }

  }

When withReadStream is set to true , selected image can be accessed as:withReadStream设置为true时,可以通过以下方式访问所选图像:

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

but when withReadStream is false :但是当withReadStreamfalse时:

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

And although file.path is null in flutter for web , the file.name is set correctly and we can display it.虽然file.pathwebflutter 中的 null ,但file.name设置正确,我们可以显示它。

More info here更多信息在这里

Another way (without file_picker package):另一种方式(没有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();
  }

You can use Image.memory()您可以使用 Image.memory()

an exemple using the package universal_html使用 package universal_html 的示例

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        body: DemoApp0(),
      ),
    ),
  );
}

class DemoApp0 extends StatefulWidget {
  DemoApp0({
    Key key,
  }) : super(key: key);

  @override
  _DemoApp0State createState() => _DemoApp0State();
}

class _DemoApp0State extends State<DemoApp0> {
  final Map<String, Uint8List> files = {};

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          TextButton(
            onPressed: ()=>pickWebFile(),
            child: Text("select file"),
          ),
          Column(
            children: files.entries
                .map((e) => Column(
                      children: [
                        Text(e.key),
                        SizedBox(
                          width: 200,
                          height: 300,
                          child: Image.memory(e.value),
                        )
                      ],
                    ))
                .toList(),
          )
        ],
      ),
    );
  }

  Future<void> pickWebFile() async {
    List<html.File> webFiles = [];
    html.InputElement uploadInput = html.FileUploadInputElement();
    uploadInput.click();
    uploadInput.onChange.listen((e) {
      webFiles = uploadInput.files;
      for (html.File webFile in webFiles) {
        var r = new html.FileReader();
        Uint8List fileData;
        r.readAsArrayBuffer(webFile);
        r.onLoadEnd.listen((e) async {
          fileData = r.result;
          if (webFile.size < 4194304) {
            setState(() {
               files[webFile.name] = fileData;
            });
           
          }
        });
      }
    });
  }
}

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

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