How do I get the url of a file after uploading to Firebase?

Once you've uploaded a file to Firebase, how can you get its URL so you can save it for later use? I want to write url to Firebase database so that other users can access the image.

I download the file like this:

public void uploadFile()
{

    StorageReference filepath = mstorageRef.child("folder").child(filename);

    Uri File= Uri.fromFile(new File(mFileName));

    filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
        {
            Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
        }
    });
}

      

I have confirmed that the files are actually being downloaded, so now I just need a URL that I can write to my database. However, when I tried to do this:

Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();

      

This gives me an error and says that This method should only be accessed from tests or within private scope

I'm not sure what this means and I also don't know why I am getting this error since I am following this example provided by Firebase.

Is there a new way to get the URL?

Also, is this URL unique to this item in particular? That is, if I save it to the database and try to access it later, can I do it?

+15


source to share


10 answers


The one you are using UploadTask.getDownloadUrl()

is deprecated. You can use StorageReference.getDownloadUrl () .

In your case, you can try this like -



 filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
    {
         filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        Uri downloadUrl = uri;
                       //Do what you want with the url
                    }
        Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
    }
});

      

Take care to StorageReference.getDownloadUrl()

return a Task which should be processed asynchronously, you cannot execute Uri downloadUrl = photoRef.getDownloadUrl().getResult();

otherwise you will getjava.lang.IllegalStateException: Task is not yet complete

+26


source


This method also works and is a little simpler.

This is not something "incredible", but it does cut your code down to a few lines. Hope this is a helpful answer.



StorageReference filepath = mstorageRef.child("folder").child(filename);
filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot){
            Uri downloadUrl = filepath.getDownloadUrl();  // here is Url for photo  
            Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
        }
});

      

+2


source


That's hot I did it

1) This is my Upload and get http url code:

UploadTask uploadTask = FirebaseStorage.getInstance().getReference().child("id").child("filename")
                                .putFile(uri);
                        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 FirebaseStorage.getInstance().getReference().child(user.getUid()).child(avatarName).getDownloadUrl();
                            }
                        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                            @Override
                            public void onComplete(@NonNull Task<Uri> task) {
                                if (task.isSuccessful()) {
                                    Uri downloadUri = task.getResult();
                                    FirebaseDatabase.getInstance().getReference().child(user.getUid())
                                            .child(avatarName)
                                            .child("avatar_image")
                                            .setValue(downloadUri.toString());
                                    Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
                                } else {
                                    // Handle failures
                                    // ...
                                    Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

      

2) This is my onActivityResult code after getting image from gallery

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        uri = data.getData();

        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));
            ivAvatarPic.setImageBitmap(bitmap);
            //ImageView imageView = (ImageView) findViewById(R.id.imageView);
            //imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

      

+1


source


As mentioned above, StorageReference.getDownloadUrl()

returns Task.

Here is my code:

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

                    filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            Uri downloadUri = uri;
                            String download_url = uri.toString();
                            mUserDatabase.child("image").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
                              @Override

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

                                   if(task.isSuccessful()) {

                                          mProgressDialog.dismiss();
                                          Toast.makeText(SettingActivity.this, "Successfully uploaded", Toast.LENGTH_LONG).show();

                                   }else {
                                       Toast.makeText(SettingActivity.this, "Error happened during the upload process", Toast.LENGTH_LONG).show();
                                   }
                                }
                            });
                        }
                    });


                }else{
                    Toast.makeText(SettingActivity.this, "Error happened during the upload process", Toast.LENGTH_LONG ).show();
                }
            }
        });

      

+1


source


Try it:

 filepath.putFile(File).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
         @Override
         public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
            if(task.isSuccessful()){
                 String fileUri = task.getResult().getUploadSessionUri().toString();
                         // Do whatever you want with fileUri 

                        }
                   }
            }) ;

      

+1


source


Use the following code

val imageGalleryRef = storageReference?.child(name + "_gallery")
            val uploadTask = imageGalleryRef.putFile(file)
            uploadTask.addOnFailureListener({ e ->
                Log.e(TAG, "onFailure sendFileFirebase " + e.message)
            }).addOnCompleteListener(
                    object : OnCompleteListener<UploadTask.TaskSnapshot> {
                        override fun onComplete(p0: Task<UploadTask.TaskSnapshot>) {
                            imageGalleryRef.downloadUrl.addOnSuccessListener { e ->
                                run {
                                     downloadUrl = e.toString() // e is image download Uri
                                }
                            }
                        }
                    }

            )

      

0


source


final StorageReference riversRef = mStoreage.child (CommonUtils.getDatetime ()); final UploadTask uploadTask = riversRef.putFile (imageUri); uploadTask.addOnSuccessListener (new OnSuccessListener () {@Override public void onSuccess (UploadTask.TaskSnapshot taskSnapshot) {progressDialog.dismiss (); // selected_image.setVisibility (View.GONE); riversRef.getDctivity) new OnSuccessListenver void onSuccess (Uri uri) {Toast.makeText (getApplicationContext (), uri.toString (), Toast.LENGTH_LONG) .show (); String caption = content.getText (). toString (); FeedData feedData = FeedData.builder (). Caption (caption) .imageUrl (uri.toString ()). PackageName (packagename) .appName (appname) .build (); feedpost (feedData);}});

                Toast.makeText(getApplicationContext(), "upload complete", Toast.LENGTH_LONG).show();
                Snackbar snackbar = Snackbar.make(getActivity().findViewById(android.R.id.content), "upload complete", Snackbar.LENGTH_INDEFINITE);
                snackbar.show();


            }
        })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        progressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                    }
                })

      

0


source


 filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                String category = spinner.getSelectedItem().toString();
                                String title = ((EditText) findViewById(R.id.post_title)).getText().toString();
                                String description = ((EditText) findViewById(R.id.post_description)).getText().toString();
                                final Post post = new Post(userId, category, title, description, latitude, longitude, true);
                                post.setAddressList(addressLine);
                                post.setContact(contact);

                                if (addressLine != null) {
                                    post.setPlace(addressLine.split(",")[2]);
                                }
                                post.setId(key);
                                post.setImage(uri.toString());
                                databaseReference.setValue(post).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if (task.isSuccessful()) {

                                            ((EditText) findViewById(R.id.post_title)).setText("");
                                            ((EditText) findViewById(R.id.post_description)).setText("");
                                            postImageButton.setImageURI(null);
                                            progressBarDialog.dismiss();
                                            Toast.makeText(PostActivity.this, "Your request is sucessfully completed", Toast.LENGTH_SHORT).show();
                                        } else if (!task.isSuccessful()) {
                                            progressBarDialog.dismiss();
                                            Toast.makeText(PostActivity.this, "Your request is not completed", Toast.LENGTH_SHORT).show();
                                        }

                                    }
                                });
                            }

                        });
                    }

      

0


source


Have you tried it taskSnapshot.getDownloadUrl()

? if that also doesn't work you can get the location of the image in success receivermstorageRef.child("folder").child(filename).toString()

-1


source


Try the following:

final Uri uri = data.getData();

StorageReference filepath = mStorageRef.child("folder").child(filename);
filepath.putFile(uri).addOnSuccessListener(new 

OnSuccessListener<UploadTask.TaskSnapshot>() {

        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            Uri downloadUri = taskSnapshot.getDownloadUrl();
            //Getting url where image is stored
            //downloadUri will store image URI
        }
    });

      

-2


source







All Articles