【问题标题】:Flutter web - Cannot upload images to Firebase StorageFlutter web - 无法将图像上传到 Firebase 存储
【发布时间】:2021-07-28 09:28:26
【问题描述】:

在flutter web中挑选图片后尝试将图片上传到firebase存储,如下所示:

void uploadImage({@required Function(File file) onSelected}) {
    print('selecting image');
    InputElement uploadInput = FileUploadInputElement()
      ..accept = 'image/*'; //it will upload only image
    uploadInput.click();
    uploadInput.onChange.listen((event) {
      final file = uploadInput.files.first;
      final reader = FileReader();
      reader.readAsDataUrl(file);
      reader.onLoadEnd.listen((event) {
        onSelected(file);
      });
    });

    //selected image
  }

  void uploadStorage() {
    //upload selected image to Firebase storage
    final dateTime = DateTime.now();
    final path = 'CategoryImage/$dateTime';
    uploadImage(onSelected: (file) {
      if (file != null) {
        setState(() {
          _fileNameTextController.text = file.name;
          _imageSelected=false;
          _url = path;
        });
        Reference firebaseStorageRef = FirebaseStorage.instance.ref('CategoryImage/$dateTime').child(file.name);
        UploadTask uploadTask = firebaseStorageRef.putFile(file);
        uploadTask.whenComplete(() async{
          String imgUrl = await firebaseStorageRef.getDownloadURL();
        });
        // fb.storage().refFromURL('gs://flutter-grocery-app-ca3ef.appspot.com').child(path).put(file);
      }
    });
  }

但它返回以下错误:

error: The argument type 'File (where File is defined in C:\src\flutter\bin\cache\pkg\sky_engine\lib\html\html_dart2js.dart)' can't be assigned to the parameter type 'File (where File is defined in C:\src\flutter\bin\cache\pkg\sky_engine\lib\io\file.dart)'. (argument_type_not_assignable at [grocery_app_admin] lib\widgets\category\category_upload_widget.dart:180)

我查看了一些解决方案,表明 dart:html 和 dart:io 之间存在冲突,因此分别导入它们,但这也不起作用。

【问题讨论】:

    标签: flutter dart firebase-storage flutter-web


    【解决方案1】:

    File 下有几个不同的类 - 在这种情况下,您需要使用 dart:html - 见下文

    import 'dart:async';
    import 'package:firebase/firebase.dart' as fb;
    import 'dart:html' as html;
    
    String url;
    
    Future<String> uploadProfilePhoto(html.File image, {String imageName}) async {
      try {
        //Upload Profile Photo
        fb.StorageReference _storage = fb.storage().ref('displayPhotos/$imageName');
        fb.UploadTaskSnapshot uploadTaskSnapshot = await _storage.put(image).future;
        // Wait until the file is uploaded then store the download url
        var imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
        url = imageUri.toString();
      } catch (e) {
        print(e);
      }
      return url;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 2020-04-30
      • 2018-10-24
      • 2019-01-22
      • 1970-01-01
      • 2020-12-20
      • 2021-07-03
      • 2021-09-18
      相关资源
      最近更新 更多