Flutter веб-файл загрузки - PullRequest
3 голосов
/ 27 января 2020

Я хочу загрузить файлы с помощью Flutter web, но я столкнулся с некоторыми проблемами, мои шаги следующие:

/// choose file
  void _chooseFile() {
    InputElement uploadInput = FileUploadInputElement();
    uploadInput.accept = ".mp4";
    uploadInput.multiple = true;
    uploadInput.click();
    uploadInput.onChange.listen((event) {
      final files = uploadInput.files;
      if (files.length == 1) {
        final file = files[0];
        final reader = FileReader();
        reader.onLoadEnd.listen((event) {
          print('loaded: ${file.name}');
          print('type: ${reader.result.runtimeType}');
          print('file size = ${file.size}');
          _uploadFile(file);
        });
        reader.onError.listen((event) {
          print(event);
        });
        reader.readAsArrayBuffer(file);
      }
    });
  }

/// upload file
/// file: in dart:html package not in dart:io package
  void _uploadFile(File file) async {
    FormData data = FormData.fromMap({
      'file': MultipartFile.fromBytes(
        List<int>, // -----------------------------> problem line
        filename: file.name,
      )
    });
    Dio dio = new Dio();
    dio.post('upload file url', data: data, onSendProgress: (count, total) {
      print('$count ==> $total');
    }).then((value) {
      print('$value');
    }).catchError((error) => print('$error'));
  }

Проблема в том, что MultipartFile.fromBytes(List<int> value, {...}), но я не знаю, как конвертировать file (в дротике: html не в дротике: io) до List<int>.

Спасибо !!!

Ответы [ 2 ]

0 голосов
/ 09 апреля 2020

тьфу ДА, помогите пожалуйста с этим, кроме данного решения - я пытаюсь преобразовать уже работающую мобильную реализацию загрузки файлов в Firebase Storage в Flutter Web:

  Future<String> _uploadWebAttachedFile(int index, html.File file) async {
    final fileName = file.name;

    final indexDigits = log(max(1, index)).toInt().floor() + 1;
    final padZeroes = 3 - indexDigits;
    final prefix = '${index.toString().padLeft(padZeroes, '0')}${index + 1}';
    final targetPath = 'chatRooms/$_chatRoomId/messages/$id/${prefix}_$fileName';

   // File newFile = File.fromRawPath(//something?);

    List<int> fileData = // THIS IS WHERE I NEED TO GET THE BYTES OF MY html.File;

    StorageReference ref = FirebaseStorage.instance.ref().child(targetPath);
    StorageUploadTask uploadTask = ref.putData(fileData);
    return (await (await uploadTask.onComplete).ref.getDownloadURL()) as String;
  }
0 голосов
/ 07 апреля 2020

Вам необходимо преобразовать reader, как показано ниже:

List<int> _selectedFile;
Uint8List _bytesData;

void _handleResult(Object result) {
    setState(() {
      _bytesData = Base64Decoder().convert(result.toString().split(",").last);
      _selectedFile = _bytesData;
    });
  }

, вызвать веселье c:

_handleResult(reader.result);

, затем передать _bytesData в MultipartFile.fromBytes(...) или верните fun c, наберите List<int> и назовите его где угодно.

Например, вот что я сделал, чтобы получить изображение:

List<int> imageFileBytes;

    /// Browse Image:
  _setImage(int index) async {
    html.InputElement uploadInput = html.FileUploadInputElement();
    uploadInput.multiple = false;
    uploadInput.draggable = true;
    uploadInput.accept = 'image/*';
    uploadInput.click();
    html.document.body.append(uploadInput);
    uploadInput.onChange.listen((e) {
      final files = uploadInput.files;
      final file = files[0];
      final reader = new html.FileReader();
      reader.onLoadEnd.listen((e) {
        var _bytesData = Base64Decoder().convert(reader.result.toString().split(",").last);
        setState(() {
          imageFileBytes = _bytesData;
        });
      });
      reader.readAsDataUrl(file);
    });

    uploadInput.remove();
  }
...