Flutter Web-将图像文件上传到Firebase存储

时间:2020-01-13 12:46:05

标签: file-upload google-cloud-functions firebase-storage image-upload flutter-web

在Flutter Web上,我从计算机中选择一个图像文件并获得一个File图像对象。然后,我要将其上传到Firebase存储。对于该应用的Android和iOS版本,我使用的是Firebase Cloud Function和一个http multipart请求。它有效,但对于该应用程序的网络版本则无效。因此,

如何直接或通过Cloud Function将html图像文件上传到Firebase存储?

7 个答案:

答案 0 :(得分:17)

最后,我设法找到了解决此问题的方法。为此,我需要安装两个依赖项,firebaseuniversal_html。 尽管很难找到解决方案,但其实现实际上很简单。这是我用来将html图像文件上传到Firebase存储到“ images”文件夹中的功能的代码:

import 'dart:async';
import 'package:universal_html/prefer_universal/html.dart' as html;
import 'package:firebase/firebase.dart' as fb;

Future<Uri> uploadImageFile(html.File image,
      {String imageName}) async {
    fb.StorageReference storageRef = fb.storage().ref('images/$imageName');
    fb.UploadTaskSnapshot uploadTaskSnapshot = await storageRef.put(image).future;
    
    Uri imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
    return imageUri;
}

我希望它可以帮助与我有相同需求的人。

答案 1 :(得分:4)

要在Flutter for Web应用程序中访问Cloud Storage,可以使用firebase-dart plugin。您可以在存储库中找到accessing storage through firebase-dart的示例。

答案 2 :(得分:4)

以下是适合我上传图片的完整片段: html.File对我不起作用,文件已上传,但是您将在Firebase存储中看到Error loading preview,因此直接传递字节对我来说是有效的。

要显示图像,您可以将mediaInfo.bytes与支持字节的小部件一起使用,例如FadeInImage,可以使用MemoryImage(mediaInfo.bytes)Image.memory(mediaInfo.bytes)

使用的软件包:

  1. firebase
  2. image_picker_web
  3. path
  4. mime_type
    Future<MediaInfo> imagePicker() async {    
        MediaInfo mediaInfo = await ImagePickerWeb.getImageInfo;
        return mediaInfo;
     }
     
     Future<Uri> uploadFile(
          MediaInfo mediaInfo, String ref, String fileName) async {
        try {
          String mimeType = mime(Path.basename(mediaInfo.fileName));

          // html.File mediaFile =
          //     new html.File(mediaInfo.data, mediaInfo.fileName, {'type': mimeType}); 
          final String extension = extensionFromMime(mimeType);

          var metadata = fb.UploadMetadata(
            contentType: mimeType,
          );

          fb.StorageReference storageReference =
              fb.storage().ref(ref).child(fileName + ".$extension");

          fb.UploadTaskSnapshot uploadTaskSnapshot =
              await storageReference.put(mediaInfo.data, metadata).future;

          Uri imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
          print("download url $imageUri");
          return imageUri;
        } catch (e) {
          print("File Upload Error $e");
          return null;
        }
      }

答案 3 :(得分:0)

相关附录:如何下载:为什么这是一个隐藏的秘密,我不知道。感谢Learn Flutter Code for this nice little tutorial.

不要将Firebase存储作为依赖项,只需将Firebase与:

import 'package:firebase/firebase.dart' as fb;

然后创建一个方法:

        Future<Uri> myDownloadURL() async {return await fb.storage().refFromURL('gs://<your storage reference>').child('$id.jpg').getDownloadURL();}

像这样从FutureBuilder调用它:

        FutureBuilder<Uri>(
        future: myDownloadURL(),
        builder: (context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return <Something as a placeholder>;
          }
          return CircleAvatar(
            radius: backgroundRadius * 2,
            child: Image.network(snapshot.data.toString()),
          );
        },
      )

答案 4 :(得分:0)

在合并了这么多帖子后,我做到了,并且奏效了!

不,您只是不需要任何类型的 Universal_HTML 或其他 image_picker_web。只需坚持使用图像选择器(https://pub.dev/packages/image_picker)。 并使用下面的代码,就像我用来将图像上传到 Firebase 存储一样,它可以在 IOS、Android、Web 的所有方式中工作,我希望您已经添加了 ios 和 android 的权限。开始吧!

Import

import 'package:firebase_storage/firebase_storage.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as Path;

Call this method when you want to open a file picker in any of the above platforms!

chooseImage() async {
PickedFile? pickedFile = await ImagePicker().getImage(
      source: ImageSource.gallery,
    );
}

now you've file in pickedFile use kIsWeb to find out if it's web or not!

uploadImageToStorage(PickedFile? pickedFile) async {
if(kIsWeb){
Reference _reference = _firebaseStorage
        .ref()
        .child('images/${Path.basename(pickedFile!.path)}');
    await _reference
        .putData(
      await pickedFile!.readAsBytes(),
      SettableMetadata(contentType: 'image/jpeg'),
    )
        .whenComplete(() async {
      await _reference.getDownloadURL().then((value) {
        uploadedPhotoUrl = value;
      });
    });
 }else{
//write a code for android or ios
}

}

答案 5 :(得分:0)

添加到 @WebRooseDevelopment 中,您可能还需要更新 index.html 文件以包含新的 Firebase 版本。

'src="https://www.gstatic.com/firebasejs/8.6.1/firebase-storage.js">'

答案 6 :(得分:0)

 void uploadImage({required Function(File? file) onSelected}) {
    var uploadInput = FileUploadInputElement()..accept = 'image/*';
    uploadInput.click();

    uploadInput.onChange.listen((event) async {
      final file = uploadInput.files!.first;

      final reader = FileReader();
      reader.readAsDataUrl(file);
      reader.onLoadEnd.listen((event) async {
        onSelected(file);
      });
    });
  }

  void uploadToStorage() {
    final dateTime = DateTime.now();
    final userId = FirebaseAuth.instance.currentUser!.uid;
    imagePath = '$userId/$dateTime'.replaceAll(' ', '');

    uploadImage(onSelected: (file) {
      try {
        fb.storage().refFromURL('{reference url from firebase}').child(imagePath).put(file);
      } catch (e) {
        print('uploadImage $e');
      }
    });
  }

点击按钮调用uploadToStorage函数并显示图片,

 Future<Uri> downloadImageUrl(String? path) {
    print(
        'downloadImageUrl:: ${fb.storage().refFromURL('{reference url from firebase}').child(path!).getDownloadURL()}');
    return fb
        .storage()
        .refFromURL('gs://onehourappbuildpractice.appspot.com/')
        .child(path)
        .getDownloadURL();
  }

FutureBuilder<Uri>(
                      future: downloadImageUrl(
                          controller.hiddenGemList[i].imagePath!),
                      builder: (context, snapshot) {
                        if (snapshot.connectionState ==
                            ConnectionState.waiting) {
                          return Center(
                            child: CircularProgressIndicator(),
                          );
                        }
                        return Container(
                            height: 100,
                            width: 200,
                            child: FadeInImage.assetNetwork(
                              image: snapshot.data.toString(),
                              placeholder: 'assets/placeholder_image.jpeg',
                            ));
                      })
相关问题