Upload image in flutter web

前端 未结 3 680
别跟我提以往
别跟我提以往 2021-01-03 16:37

Flutter web is still in technical preview but i want to pick an image from the disk and upload it to the server. Is there anyway to add HTML, JS to my flutter web project a

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 17:04

    You need addEventListener and also need to append it for woking it on mobile safari. I answered here too.

    Future _setImage() async {
        final completer = Completer>();
        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> 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 images = await completer.future;
        setState(() {
            _uploadedImages = images;
        });
        uploadInput.remove();
    }
    

    This also works:

    Future _setImage() async {   
        final completer = Completer>();
        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 files = input.files;
          Iterable> 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 images = await completer.future;
        setState(() {
          _uploadedImages = images;
        });
        input.remove();
    }
    

提交回复
热议问题