Flutter web - 无法将图像上传到 Firebase 存储

Posted

技术标签:

【中文标题】Flutter web - 无法将图像上传到 Firebase 存储【英文标题】:Flutter web - Cannot upload images to Firebase Storage 【发布时间】: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 之间存在冲突,因此分别导入它们,但这也不起作用。

【问题讨论】:

【参考方案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;

【讨论】:

以上是关于Flutter web - 无法将图像上传到 Firebase 存储的主要内容,如果未能解决你的问题,请参考以下文章

将图像/文件上传到 Strapi (Flutter Web)

在运行时将图像从计算机上传并显示到 FLUTTER WEB APP

无法使用 Flutter 将文件上传到 FirebaseStorage

将用户上传到 Flutter Web 的图片存储为实际的 .jpg 文件

在 Flutter Web 中上传多个文件(图像)

将 Flutter 应用迁移到 Flutter Web 时如何显示图像资产?