如何在flutter中上传Firebase存储器中的图像

kknvjkwl  于 2023-03-09  发布在  Flutter
关注(0)|答案(1)|浏览(157)

我从Firebase存储器中获取图像,用相机拍摄照片,或者从库中选择一个,当其中一个完成时,我有一个类来存储图像,以便在需要时使用它。
要选择图像(画廊,相机等),首先你可以使用图像选择器包。

final pickedFile = await picker.getImage(source: ImageSource.camera);

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

然后检测你想要保存这个文件映像的引用

//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();
    • 代码**
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;
   }
bt1cpqcv

bt1cpqcv1#

您提供的代码基本正确。但是,代码中有一个小错误,您将变量image声明为File,但后来将file传递给reference.putFile(file)。您应该将file更改为image
此外,downloadUrl在最新版本的Firebase存储插件中已被弃用。您应该改用ref.getDownloadURL()
下面是正确的代码:

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(image);

  // Waits till the file is uploaded then stores the download url 
  String location = await reference.getDownloadURL();

  // Return the download url 
  return Uri.parse(location);
}

注意,getDownloadURL()方法返回一个String,因此应该使用Uri.parse()将其解析为一个URI。

相关问题