如何将图像文件存储到FirebaseStorage

时间:2019-05-25 17:47:05

标签: android

当我初始化mStorageRef = FirebaseStorage.getInstance()。getReference(“ uploads”);时         mDatabaseRef = FirebaseDatabase.getInstance()。getReference(“ uploads”);,我的应用已停止 我的android SDK版本28;  buildToolsVersion '28 .0.3'

致命异常: 无法解决以下问题:Lcom / google / android / gms / common / internal / zzbq;         com.google.firebase.storage.FirebaseStorage.getInstance(未知来源:11)

1 个答案:

答案 0 :(得分:0)

在这里我没有弄错您在做什么,让我为您编写整个代码来解决您的问题。

FirebaseStorage firebaseStorage;
StorageReference storageReference;

private Button btnChoose, btnUpload;
private ImageView imageView;

private Uri filePath;

private final int IMAGE_REQUEST = 71;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    storage = FirebaseStorage.getInstance();
    storageReference = storage.getReference();
    btnChoose = (Button) findViewById(R.id.btnChoose);
    btnUpload = (Button) findViewById(R.id.btnUpload);
    imageView = (ImageView) findViewById(R.id.imgView);

    btnChoose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chooseImage();
        }
    });

    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            uploadImage();
        }
    });

}

private void chooseImage() {
    //an intent to choose your required image.
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select your photo."), IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK
            && data != null && data.getData() != null) {
        filePath = data.getData();
        //this will update your imageView
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        imageView.setImageBitmap(bitmap);
    }
}

private void uploadImage() {

    if (filePath != null) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading your image");
        progressDialog.show();


        //Put uid of the user to make it easy to get your image back when needed. I would suggest you to use an external
        //library to compress the image for best performance.
        StorageReference ref = storageReference.child("uploads/" + "PUT_UID_OF_USER");

        //method to upload a file.
        ref.putFile(filePath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        //if the image is successfully uploaded
                        progressDialog.dismiss();
                        Toast.makeText(Activity.this, "Uploaded", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        //if image upload was failed due to some reason.
                        progressDialog.dismiss();
                        Toast.makeText(Activity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
                                .getTotalByteCount());

                        //this will actually show the progress in the progress dialog.
                        progressDialog.setMessage("Uploaded " + (int) progress + "%");
                    }
                });
    }
}

//use picasso library for this for the best performance/result.
private void getImageBack(String uid_of_user){

    StorageReference ref = storageReference.child("uploads/" + "PUT_UID_OF_USER").getImage("PUT_NAME_OF_IMAGE");

    load.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            // Got the download URL for 'users/me/profile.png'
            // Pass it to Picasso to download, show in ImageView and caching
            Picasso.with(Test.this).load(uri.toString()).into(imageView);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle any errors
            Toast.makeText(Test.this, "failed", Toast.LENGTH_SHORT).show();
        }
    });


}

代码未经测试,可能会出错,您可以在任何需要的地方使用我的帮助:)

在Google上搜索毕加索图书馆,这是一个非常著名的图书馆。