无法获取上载文件的网址

时间:2018-06-28 09:39:11

标签: android firebase firebase-realtime-database firebase-storage

我正在尝试获取上载文件的URL,但是我得到了:com.google.android.gms.tasks.zzu@a12a0cb或类似的内容。

这是我尝试过的代码(kotlin):

val uid = UUID.randomUUID().toString()

val storageRef = FirebaseStorage.getInstance().reference.child("content/$uid/$uid.jpg")

storageRef.putFile(file).addOnSuccessListener { taskSnapShot ->
    val downloadUrl = storageRef.downloadUrl
    FirebaseDatabase.getInstance().reference.child("Photos").child(date).push().setValue(downloadUrl)
}

但是它不起作用。我也尝试了以下代码:

val uid = UUID.randomUUID().toString()

val storageRef = FirebaseStorage.getInstance().reference.child("content/$uid/$uid.jpg")

storageRef.putFile(file).addOnSuccessListener (
      object : OnSuccessListener<UploadTask.TaskSnapshot> {
          override fun onSuccess(taskSnapshot: UploadTask.TaskSnapshot?) {
              val downloadUrl = storageRef.downloadUrl
              FirebaseDatabase.getInstance().reference.child("Photos").child(date).push().setValue(downloadUrl)
          }
      }
)

但是结果是一样的。我仍然将com.google.android.gms.tasks.zzu@a12a0cb而不是URL插入到数据库中。我做错了什么?我已经花费了一整天的时间试图找出答案,请帮忙。

7 个答案:

答案 0 :(得分:2)

我有同样的问题。我刚刚解决了。 我不能确切地说出为什么它不能与其他语法一起使用,但是我这样做的结果是:(Firebase实现版本:16.0.1 / Kotlin)

mReference.putFile (uri) .addOnFailureListener {
          // failure
       } .addOnSuccessListener () {taskSnapshot -> 
         // success
             mReference.downloadUrl.addOnCompleteListener () {taskSnapshot ->

                 var url = taskSnapshot.result
                 println ("url =" + url.toString ())

             }
  }

答案 1 :(得分:1)

这是我的项目代码的一部分,与您的问题相同,但是现在在进行必要的修改后可以正常工作,进行相应的更改。

final StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");


            filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task) {

                    filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {

                            if (task.isSuccessful()){

                                String download_url=uri.toString();//Here is the URL

                                mUserDatabase.child("image").setValue(download_url)/*Storing the URL in the Firebase database*/
                                 .addOnCompleteListener(new OnCompleteListener<Void>() {

                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {

                                        if (task.isSuccessful()) {

                                            /*mProgressDialog.dismiss();
                                            Toast.makeText(SettingsActivity.this, "Success Uploading", Toast.LENGTH_LONG).show();*/

                                        }
                                    }
                                });

                            }else {
                                /*Toast.makeText(SettingsActivity.this, "Error in uploading!", Toast.LENGTH_LONG).show();
                                mProgressDialog.dismiss();*/
                            }

                        }
                    });

                }
            });

答案 2 :(得分:0)

您可能正在使用旧版本的Firebase存储。不建议使用获取URL的方式,请查看更改日志Cloud Storage version 16.0.1

我没有Kotlin代码,但是Java代码是

final StorageReference ref = storageRef.child("images/mountains.jpg");
uploadTask = ref.putFile(file);

Task<Uri> urlTask = uploadTask.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 ref.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
        } else {
            // Handle failures
            // ...
        }
    }
});

您可以在Firebase Storage的Android文档的“ Android”>“ Upload Files”>“获取下载URL”部分中找到此代码

答案 3 :(得分:0)

此代码对我有用

//Data is the uri of the file
  UploadTask uploadTask =mProfileStorageRef.child("profilePic").putFile(data);
 uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task) {

            task.getResult().getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {

                    if (task.isSuccessful()) {

                        //Url is here
                        String url = uri.toString();



                            }
                        });

答案 4 :(得分:0)

如果您使用的是Kotlin,则此代码基于官方文档,并且非常有用。

    fun fileUpload() {


    mFireBaseStorage = FirebaseStorage.getInstance()
    mphotoStorageReference = mFireBaseStorage.getReference().child("alvaras")

    //in case you want to compress your bitmap before upload
    val bmp: Bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath) //filepath is the URI from the onActivityResult
    val baos: ByteArrayOutputStream = ByteArrayOutputStream()
    bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos) //25 is the compression, cane be anything between 1 and 100, but 100 is no compression

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

var uploadTask = mphotoStorageReference.putFile(filePath)

    val urlTask = uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
        if (!task.isSuccessful) {
            task.exception?.let {
                throw it
            }
        }
        return@Continuation mphotoStorageReference.downloadUrl
    }).addOnCompleteListener { task ->
        if (task.isSuccessful) {
            val downloadUri = task.result

            urifinal = downloadUri.toString() //this is the url you want
            val imageView: ImageView = findViewById(R.id.imageView1)

            //show it in a imageview with glide with the url
            Glide.with(this@MapsActivity).load(urifinal).into(imageView)
            imageView.visibility = View.VISIBLE

        } else {
            // Handle failures
        Toast.makeText(this, "An error occur", Toast.LENGTH_SHORT).show()
            // ...
        }
    }


    }

答案 5 :(得分:0)

获取下载URL的关键是要了解有多个array.array值正在被用来最终获得实际的np.array

Task实际上本身返回一个Uri。然后,我们从该dbRef.downloadUrl中检索上传文件的Uri。

这是一个伪代码:

Task

希望这是有道理的。现在已淘汰了许多较旧的方法,最好参考文档以获得更好的主意: https://firebase.google.com/docs/storage/android/upload-files

答案 6 :(得分:0)

使用Kotlin

官方文档中有一个小错误

但已更正here