Flutter-将图像上传到Firebase存储

时间:2018-08-15 11:26:02

标签: image file firebase flutter firebase-storage

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

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

我如何拿走我的Image并从中获取FileUint8List进行上传?

-

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

无论哪种方式,只要提供正确的数据类型即可上传图片,无论图片的开头还是结尾都是File

9 个答案:

答案 0 :(得分:7)

使用图像选择器选择图像时,它会返回一个文件,您可以使用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;
   }

答案 1 :(得分:4)

对不起,我的回答很晚,但以上答案有些陈旧,希望我的回答对您有所帮助。下面的代码示例将在以下依赖项上工作。

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

pubspec.yaml

dependencies
    image_picker: ^0.6.5
    firebase_storage: ^3.1.5

飞镖代码

//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 
     }

}

答案 2 :(得分:4)

要先选择图像(图库,照相机等),您可以使用图像选择器package

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

library(data.table)
DT <- data.table(grp  = rep(LETTERS[1:3], 3), 
                 val  = 1:9, 
                 val2 = rep(letters[24:26], each = 3))

keepcols <- setdiff(colnames(DT), "grp") 
DT[, val3 := letters[1:9]]
# if you want to keep all of val3; otherwise switch the previous two lines

DT[, (keepcols) := .SD[which.min(val)], by=.(grp), .SDcols=keepcols][]
#>    grp val val2 val3
#> 1:   A   1    x    a
#> 2:   B   2    x    b
#> 3:   C   3    x    c
#> 4:   A   1    x    d
#> 5:   B   2    x    e
#> 6:   C   3    x    f
#> 7:   A   1    x    g
#> 8:   B   2    x    h
#> 9:   C   3    x    i

然后检测您要保存此文件图像的引用

//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;
  }

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

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

完整代码

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

答案 3 :(得分:3)

同时,有一个库可以帮助您...

  1. 选择
  2. 裁剪,压缩
  3. 上传 图片到Firebase存储。

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

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

Firebase图片上传器示例:

Firebase Picture Uploader Example

答案 4 :(得分:1)

如果您使用 firebase_storage >= 5.0.0-dev.1,则 StorageReference 类已重命名为 Reference

我的意思是较新版本的 Firebase 不使用以下格式:

// 将带有文件名的路径传递给 Firebase 存储参考 StorageReference reference = FirebaseHelper.firebaseStorage (). Child ("your_path/ $ fileName");

正确的应该是: Reference reference = FirebaseHelper.firebaseStorage (). Child ("your_path / $ fileName");

答案 5 :(得分:0)

我不确定您的Image类型是什么。在Flutter框架中有is an Image class,它是一个小部件,而不是您从相机中得到的。

在Flutter中,图像通常只是一个File,这意味着putFile应该可以正常工作。

FirebaseStorage.instance.ref().child(path).putFile(image)

如果我发布的内容无效,请添加有关您的实际类型的信息。

答案 6 :(得分:0)

从图库或照相机中选择图像时

只需使用下面提到的功能即可获取带有扩展名的文件名

basename(image.path)

,然后将文件以及您要上传到的路径(带有文件名)传递到firebase存储参考,则不必考虑文件的扩展名。

使用的图书馆

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

代码:

upload() async {
   //pick image   use ImageSource.camera for accessing camera. 
   File image = await ImagePicker.pickImage(source: ImageSource.gallery);

   //basename() function will give you the filename
   String fileName = basename(image.path);

   //passing your path with the filename to Firebase Storage Reference
   StorageReference reference =
        FirebaseHelper.firebaseStorage().child("your_path/$fileName");

   //upload the file to Firebase Storage
   StorageUploadTask uploadTask = reference.putFile(image);

   //Snapshot of the uploading task
   StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
}

答案 7 :(得分:0)

  

firebase_storage:^ 3.0.6,     image_picker:^ 0.6.1   您必须使用这两个库

获取图像后

  Future getImage() async {
    var tempImage = await ImagePicker.pickImage(source: ImageSource.gallery);

    setState(() {
      sampleImage = tempImage;
     });
  }

现在上传图片

Widget enableUpload() {
return Container(
  child: Column(
    children: <Widget>[
      Image.file(sampleImage, height: 300.0, width: 300.0),
      RaisedButton(
        elevation: 7.0,
        child: Text('Upload'),
        textColor: Colors.white,
        color: Colors.blue,
        onPressed: () {
          final StorageReference firebaseStorageRef =
              FirebaseStorage.instance.ref().child('myimage.jpg');
          final StorageUploadTask task =
              firebaseStorageRef.putFile(sampleImage);

        },
      )
    ],
  ),
);
}

您可以在所需的位置使用此enableUpload()小部件。

答案 8 :(得分:0)

ImagePicker 有助于从图库/相机中获取文件并使用 FirebaseStorage 上传。 getDownloadURL() 方法为我们提供了上传到 firebase 的下载 URL。

Future uploadImageToFirebase(BuildContext context) async {
        final picker = ImagePicker();
        final pickedFile = await picker.getImage(source: ImageSource. gallery);
        File image = new File(pickedFile.path);

        var reference = FirebaseStorage.instance.ref().child('last_image/car5'); // Modify this path/string as your need
        StorageUploadTask uploadTask = reference.putFile(file);
        StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
        taskSnapshot.ref.getDownloadURL().then(
              (value) => print("Download URL: $value"),
            );
      }