1

我想在flutter web上上传图片,但是像image_picker这样的pub我知道只支持Android和iOS,而Flutter Web不支持。我知道的另一个 pub 是 pub image,但我不知道如何在 flutter web 上使用 pub image .. 我希望分享您关于使用 pub image 或其他 pub 上传支持 Flutter web 的图像的知识..

4

2 回答 2

5

我正在寻求相同的解决方案。实际上 onChange 在移动 safari 上效果不佳,它需要更改 addEventListener 并且还需要附加它。

  Future<void> _setImage() async {
    final completer = Completer<List<String>>();
    InputElement uploadInput = FileUploadInputElement();
    uploadInput.multiple = true;
    uploadInput.accept = 'image/*';
    uploadInput.click();
    //* onChange doesn't work on mobile safari
    uploadInput.addEventListener('change', (e) async {
      // read file content as dataURL
      final files = uploadInput.files;
      Iterable<Future<String>> resultsFutures = files.map((file) {
        final reader = FileReader();
        reader.readAsDataUrl(file);
        reader.onError.listen((error) => completer.completeError(error));
        return reader.onLoad.first.then((_) => reader.result as String);
      });

      final results = await Future.wait(resultsFutures);
      completer.complete(results);
    });
    //* need to append on mobile safari
    document.body.append(uploadInput);
    final List<String> images = await completer.future;
    setState(() {
      _uploadedImages = images;
    });
    uploadInput.remove();
  }

这也有效:

Future<void> _setImage() async {   
    final completer = Completer<List<String>>();
    final InputElement input = document.createElement('input');
    input
      ..type = 'file'
      ..multiple = true
      ..accept = 'image/*';
    input.click();
    // onChange doesn't work on mobile safari
    input.addEventListener('change', (e) async {
      final List<File> files = input.files;
      Iterable<Future<String>> resultsFutures = files.map((file) {
        final reader = FileReader();
        reader.readAsDataUrl(file);
        reader.onError.listen((error) => completer.completeError(error));
        return reader.onLoad.first.then((_) => reader.result as String);
      });
      final results = await Future.wait(resultsFutures);
      completer.complete(results);
    });
    // need to append on mobile safari
    document.body.append(input);
    // input.click(); can be here
    final List<String> images = await completer.future;
    setState(() {
      _uploadedImages = images;
    });
    input.remove();
}
于 2019-12-19T06:44:36.170 回答
1

你可以使用FileUploadInputElementdart:html 的类。

import 'dart:html';

实现以下代码以启动文件选择器:

_startFilePicker() async {
InputElement uploadInput = FileUploadInputElement();
uploadInput.click();

uploadInput.onChange.listen((e) {
  // read file content as dataURL
  final files = uploadInput.files;
  if (files.length == 1) {
    final file = files[0];
    final reader = new FileReader();

    reader.onLoadEnd.listen((e) {
      _handleResult(reader.result);
    });
    reader.readAsDataUrl(file);
  }
});
}

参考

于 2019-07-31T13:51:19.690 回答