簡體   English   中英

如何在 web 中使用 file_picker 顯示選取的圖像?

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

如何在web平台中顯示文件路徑為nullfile_picker中的file_picker拾取的圖像?

如果路徑不是 null,則使用Image.file(File)顯示圖像太容易了:

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

但它無法為 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
    }

  }

withReadStream設置為true時,可以通過以下方式訪問所選圖像:

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

但是當withReadStreamfalse時:

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

雖然file.pathwebflutter 中的 null ,但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();
  }

您可以使用 Image.memory()

使用 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