Android:上传图片位图后从Firestorage获取下载URL

时间:2018-06-21 15:23:49

标签: android google-cloud-datastore

我的Firestore参考:

  storageRef = FirebaseStorage.getInstance().getReference().child("/folder/photo.jpg");

我使用相机意图获取图像:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
            }

关于活动结果,我得到图像并上传:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] data = baos.toByteArray();
            ByteArrayInputStream bs = new ByteArrayInputStream(data);
            UploadTask uploadTask = storageRef.putStream(bs);
            uploadTask.addOnSuccessListener(taskSnapshot -> {

           new L().info(storageRef.getDownloadUrl()+"");
            new AlertUtil().showCustomAlert(this,"done");
        });
        }
    }

但是storageRef.getDownloadUrl()返回此:

com.google.android.gms.tasks.zzu@64b8bf6

代码来自文档: [https://firebase.google.com/docs/storage/android/upload-files][1]

我在这里想念什么?如何获取下载网址

2 个答案:

答案 0 :(得分:2)

Uri selectedImageUri = data.getData();
StorageReference photoRef = mSRreference.child(selectedImageUri.toString());
photoRef.putFile(selectedImageUri).addOnSuccessListener(new 
OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot){
        // your download uri - taskSnapshot.getDownloadUrl()
    }

    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
        }
});

答案 1 :(得分:1)

我尝试了文档中的Task<Uri> urlTask = uploadTask.continueWithTask...代码,但没有用。

所以我尝试上传文件,然后获取图像url,这似乎是最简单的方法,并且有效:

  UploadTask uploadTask = storageRef.putStream(bs);
            uploadTask.addOnSuccessListener(taskSnapshot -> {
                storageRef.getDownloadUrl().addOnCompleteListener(task ->
                        new L().info("url" + task.getResult()));
            });

我想指出,该文档不是很好。我正在使用Java 1.8,因此使用了较短的lamba语法。添加

compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    } 

构建您的应用。gradle这样做。