Flutter-将图像上传到Firebase存储

Jos*_*ane 6 image file firebase flutter firebase-storage

我从Firebase Storage获取图像,用相机拍摄照片,或从媒体库中选择一个。当其中一个完成时,我有一个存储一个的类,Image以便在需要时可以使用它。

现在,我需要将此图像上传到Firebase存储(已修改或新的都无所谓)。Firebase允许我使用以下之一:putDataputFile,每个需要分别为Uint8ListFile

我怎样才能拿到我的,Image然后从中获取一个FileUint8List从中上传?

-

或者,要解决此问题,File当我从Firebase Storage检索图像时如何获得图像?

无论哪种方式,都会提供正确的数据类型来上传图像,无论图像是File在开始还是结束时都显示为。

Nas*_*ash 9

使用图像选择器选择图像时,它会返回一个文件,您可以使用它await来等待,直到用户选择一个文件,然后将其存储为文件。这是一些示例代码,说明如何从图像选择器获取文件并将其上传到Firebase。

    FirebaseStorage _storage = FirebaseStorage.instance;

    Future<Uri> uploadPic() async {

    //Get the file from the image picker and store it 
    File image = await ImagePicker.pickImage(source: ImageSource.gallery);  

    //Create a reference to the location you want to upload to in firebase  
    StorageReference reference = _storage.ref().child("images/");

    //Upload the file to firebase 
    StorageUploadTask uploadTask = reference.putFile(file);

    // Waits till the file is uploaded then stores the download url 
    Uri location = (await uploadTask.future).downloadUrl;

    //returns the download url 
    return location;
   }
Run Code Online (Sandbox Code Playgroud)

  • 我知道这是一个旧答案,但只是想检查一下这是否仍然有效。uploadTask 上不存在 future。 (4认同)
  • 上述方式已被弃用,现在您必须执行以下操作:/sf/answers/4533507331/ (2认同)

Abe*_*hun 7

抱歉我的回答晚了,但上面的答案有点旧了,希望我的回答能对你有所帮助。下面的代码示例将适用于以下依赖项。

关于这个问题,它说我上传后如何检索它。您可以使用下载 URL来获取文件或图像,您可以下载它,也可以将其显示在NetworkImage小部件上以将其显示给您的用户。我在下面展示了如何获取下载 URL。

pubspec.yaml

dependencies
    image_picker: ^0.6.5
    firebase_storage: ^3.1.5
Run Code Online (Sandbox Code Playgroud)

飞镖代码

//Creating a global Variable    
StorageReference storageReference = FirebaseStorage.instance.ref();
File _image;

void getImage(){
    _image = await ImagePicker.pickImage(source: ImageSource.gallery); 
}

void addImageToFirebase(){


    //CreateRefernce to path.
    StorageReference ref = storageReference.child("yourstorageLocation/");

    //StorageUpload task is used to put the data you want in storage
    //Make sure to get the image first before calling this method otherwise _image will be null.

    StorageUploadTask storageUploadTask = ref.child("image1.jpg").putFile(_image);

     if (storageUploadTask.isSuccessful || storageUploadTask.isComplete) {
          final String url = await ref.getDownloadURL();
          print("The download URL is " + url);
     } else if (storageUploadTask.isInProgress) {

          storageUploadTask.events.listen((event) {
          double percentage = 100 *(event.snapshot.bytesTransferred.toDouble() 
                               / event.snapshot.totalByteCount.toDouble());  
          print("THe percentage " + percentage.toString());
          });

          StorageTaskSnapshot storageTaskSnapshot =await storageUploadTask.onComplete;
          downloadUrl1 = await storageTaskSnapshot.ref.getDownloadURL();

          //Here you can get the download URL when the task has been completed.
          print("Download URL " + downloadUrl1.toString());

     } else{
          //Catch any cases here that might come up like canceled, interrupted 
     }

}
Run Code Online (Sandbox Code Playgroud)


Mah*_*eja 5

要首先选择图像(画廊,相机等),您可以使用图像选择器

然后像这样获取图像作为文件

//Get the file from the image picker and store it
final pickedFile = await picker.getImage(source: ImageSource.camera);

  File image;
  if (pickedFile != null) {
    image = File(pickedFile.path);
  } else {
    print('No image selected.');
    return;
  }
Run Code Online (Sandbox Code Playgroud)

然后检测您要保存此文件图像的参考

FirebaseStorage storage = FirebaseStorage.instance;
//Create a reference to the location you want to upload to in firebase
StorageReference reference = storage.ref().child("profileImages/myImageUid");
Run Code Online (Sandbox Code Playgroud)

最后开始上传并等待完成然后获取 URL 图片

//Upload the file to firebase
        StorageUploadTask uploadTask = reference.putFile(image);
    
        StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    
        // Waits till the file is uploaded then stores the download url
        String url = await taskSnapshot.ref.getDownloadURL();
    
Run Code Online (Sandbox Code Playgroud)

完整代码

FirebaseStorage storage = FirebaseStorage.instance;

    File image;
    try {
      //Get the file from the image picker and store it
      image = await ImagePicker.pickImage(source: ImageSource.gallery);

    } on PlatformException catch (e) {
      //PlatformException is thrown with code : this happen when user back with don't
      //selected image or not approve permission so stop method here 
      // check e.code to know what type is happen
      return;
    }

    //Create a reference to the location you want to upload to in firebase
    StorageReference reference =
        storage.ref().child("profileImages/${user.id}");

    //Upload the file to firebase
    StorageUploadTask uploadTask = reference.putFile(image);

    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;

    // Waits till the file is uploaded then stores the download url
    String url = await taskSnapshot.ref.getDownloadURL();
Run Code Online (Sandbox Code Playgroud)


Chr*_*sRo 5

同时,有一个图书馆可以帮助您...

  1. 选择
  2. 裁剪、压缩
  3. 将图像上传到 firebase 存储。

该库称为firebase_picture_uploader,可以像这样使用(摘自):

new PictureUploadWidget(
  onPicturesChange: profilePictureCallback,
  initialImages: _profilePictures,
  settings: PictureUploadSettings(onErrorFunction: onErrorCallback),
  buttonStyle: const PictureUploadButtonStyle(),
  buttonText: 'Upload Picture',
  enabled: true,
)
Run Code Online (Sandbox Code Playgroud)

Firebase 图片上传器示例:

Firebase 图片上传器示例