简体   繁体   English

无法从 Firebase 存储中检索图像的下载 URL(出现异常)[需要紧急帮助]

[英]Unable to retrieve image's download URL from Firebase Storage (getting exception) [NEED URGENT HELP]

The code successfully uploads an image to Firebase Storage but doesn't give back the download URL.该代码成功地将图像上传到 Firebase 存储,但没有返回下载 URL。 How can I fix this?我怎样才能解决这个问题?

I get this exception: java.lang.IllegalArgumentException: getDownloadUrl() is not supported at the root of the bucket.我得到这个异常: java.lang.IllegalArgumentException: getDownloadUrl() is not supported at the root of the bucket. Why?为什么?

private void uploadFile() {
    if (mImageUri != null) {
        StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
                + "." + getFileExtension(mImageUri));

        fileReference.putFile(mImageUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (!task.isSuccessful()) {
                    throw task.getException();
                }

                // Continue with the task to get the download URL
                return mStorageRef.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                        System.out.println("Upload success: " + downloadUri);
                } else {
                    // Handle failures
                    // ...
                }
            }
        });

    } else {
        Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
    }

}

I think there is problem in returning downloading url, try below code:我认为返回下载网址有问题,请尝试以下代码:

private void uploadFile() {
    if (mImageUri != null) {
        StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
                + "." + getFileExtension(mImageUri));

        fileReference.putFile(mImageUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (!task.isSuccessful()) {
                    throw task.getException();
                }

                // Continue with the task to get the download URL
                //change made here
                return fileReference.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                        System.out.println("Upload success: " + downloadUri);
                } else {
                    // Handle failures
                    // ...
                }
            }
        });

    } else {
        Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
    }

}

So I have the same problem.所以我有同样的问题。 I had a code that I´ve been using for two years but something seems to have changed in Firebase.我有一个已经使用了两年的代码,但在 Firebase 中似乎发生了一些变化。 Bellow is a new code that works and solve this problems. Bellow 是一个可以工作并解决这个问题的新代码。 Ps: It´s in kotlin but you can have android sample in reference link and just adjust to my code. Ps:它在 kotlin 中,但您可以在参考链接中找到 android 示例,然后根据我的代码进行调整。

first declare a global variable private lateinit var filePath: Uri首先声明一个全局变量 private lateinit var filePath: Uri

Then place your image inside this uri file.然后将您的图像放入此 uri 文件中。

then go to the code where you want to make the upload:然后转到您要上传的代码:

    mFireBaseStorage = FirebaseStorage.getInstance()
    mphotoStorageReference = mFireBaseStorage.reference  //storage references

    val storageRef = mphotoStorageReference.child("usuarios_img")  //path in storage. This is the folder name in storage

    val bmp: Bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath)
    val baos: ByteArrayOutputStream = ByteArrayOutputStream()
    bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos) //choose compreess rate (100 means no compression)

    //get the uri from the bitmap
    val tempUri: Uri = getImageUri(this, bmp)
    //transform the new compressed bmp in filepath uri
    filePath = tempUri  //filePath is a global variable Uri


   
   var uploadTask = storageRef.child("the_name_of_the_file).putFile(filePath)

    // [START upload_get_download_url]
    val ref = storageRef
    uploadTask = ref.putFile(filePath)

    val urlTask = uploadTask.continueWithTask { task ->
        if (!task.isSuccessful) {
            task.exception?.let {
                throw it
            }
        }
        ref.downloadUrl
    }.addOnCompleteListener { task ->
        if (task.isSuccessful) {
            val downloadUri = task.result
            Log.d("test", "worked, this is the url link "+downloadUri)
            
           
        } else {
            // Handle failures
            Log.d("test", "error")

        }
    }

Thats all.就这样。

Reference https://firebase.google.com/docs/storage/android/upload-files?hl=pt-br参考https://firebase.google.com/docs/storage/android/upload-files?hl=pt-br

Hope it helps because I've lost some hours in it.希望它有所帮助,因为我已经失去了几个小时。

I have solved the solution for this.我已经解决了这个问题。 But I'm using Kotlin.但我正在使用 Kotlin。 I hope this will helps the others developer.我希望这将有助于其他开发人员。 I put some explanation about it.我对此做了一些解释。

    storageReference.child(Constant.EDUCATION).child(id).putFile(dataUpload!!.data!!)
        .addOnProgressListener {
            handleOnProgressUpload(it)
        }.addOnSuccessListener { task ->
            //At here onSuccess, we get the task to get the downloadUrl
            task.storage.downloadUrl.addOnSuccessListener {
                val downloadUrl = it.toString()
                handleSuccessDownloadUrl(downloadUrl)
            }
        }
<style name="Widget.Material.TextView.ListSeparator" parent="Widget.TextView.ListSeparator">
    <item name="background">@drawable/list_section_divider_material</item>
    <item name="textAllCaps">true</item>

 - </style>

<style name="Widget.Material.Light.TextView.ListSeparator" parent="Widget.Material.TextView.ListSeparator"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM