Java 如何从 Firebase Storage getDownloadURL 获取 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37374868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:14:54  来源:igfitidea点击:

How to get URL from Firebase Storage getDownloadURL

javaandroidfirebasefirebase-storage

提问by Jonathan Fager

I'm trying to get the "long term persistent download link" to files in our Firebase storage bucket. I've changed the permissions of this to

我正在尝试获取 Firebase 存储桶中文件的“长期持久下载链接”。我已将其权限更改为

service firebase.storage {
  match /b/project-xxx.appspot.com/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

And my javacode looks like this:

我的 javacode 看起来像这样:

private String niceLink (String date){
    String link;
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    link = dateRef.getDownloadUrl().toString();
    return link;
}

When I run this I get the uri link that looks something like com.google.android.gms.tasks.zzh@xxx

当我运行它时,我得到的 uri 链接看起来像 com.google.android.gms.tasks.zzh@xxx

Question 1.Can I from this get the download link similar to: https://firebasestorage.googleapis.com/v0/b/project-xxxx.appspot.com/o/20-5-2016.csv?alt=media&token=b5d45a7f-3ab7-4f9b-b661-3a2187adxxxx

问题 1.我可以从中获得类似于以下内容的下载链接:https: //firebasestorage.googleapis.com/v0/b/project-xxxx.appspot.com/o/20-5-2016.csv?alt=media&token= b5d45a7f-3ab7-4f9b-b661-3a2187adxxxx

When trying to get the link above I changed the last row before my return, like this:

在尝试获取上面的链接时,我在返回前更改了最后一行,如下所示:

private String niceLink (String date){
    String link;
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    link = dateRef.getDownloadUrl().getResult().toString();
    return link;
}

But when doing this i get a 403 error, and the app crashing. The consol tells me this is bc user is not logged in /auth. "Please sign in before asking for token"

但是在执行此操作时,我收到 403 错误,并且应用程序崩溃。consol 告诉我这是 bc 用户未登录 /auth。“请先登录再索取令牌”

Question 2.How do I fix this?

问题 2.我该如何解决这个问题?

采纳答案by Benjamin Wulfe

Please refer to the documentation for getting a download URL.

请参阅文档以获取下载 URL

When you call getDownloadUrl(), the call is asynchronous and you must subscribe on a success callback to obtain the results:

当您调用 时getDownloadUrl(),该调用是异步的,您必须订阅成功回调才能获得结果:

// Calls the server to securely obtain an unguessable download Url
private void getUrlAsync (String date){
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    dateRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
    {
        @Override
        public void onSuccess(Uri downloadUrl) 
        {                
           //do something with downloadurl
        } 
    });
}

This will return a public unguessable download url. If you just uploaded a file, this public url will be in the success callback of the upload (you do not need to call another async method after you've uploaded).

这将返回一个公共的不可猜测的下载 url。如果你刚刚上传了一个文件,这个公共url会在上传成功回调中(你上传后不需要调用另一个异步方法)。

However, if all you want is a Stringrepresentation of the reference, you can just call .toString()

但是,如果您想要的String只是引用的表示,则可以调用.toString()

// Returns a Uri of the form gs://bucket/path that can be used
// in future calls to getReferenceFromUrl to perform additional
// actions
private String niceRefLink (String date){
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    return dateRef.toString();
}

回答by Raj

StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();

final   StorageReference fileupload=mStorageRef.child("Photos").child(fileUri.getLastPathSegment());
UploadTask uploadTask = fileupload.putFile(fileUri);

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();
        }
        return ref.getDownloadUrl();

    }
    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
        @Override
        public void onComplete(@NonNull Task<Uri> task) {
            if (task.isSuccessful()) {
                Uri downloadUri = task.getResult();
                Picasso.get().load(downloadUri.toString()).into(image);

            } else {
                 // Handle failures
            }
       }
});

回答by Subhojit Halder

//Firebase Storage - Easy to Working with uploads and downloads.

//Firebase 存储 - 易于上传和下载。

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == RC_SIGN_IN){
        if(resultCode == RESULT_OK){
            Toast.makeText(this,"Signed in!", LENGTH_SHORT).show();
        } else if(resultCode == RESULT_CANCELED){
            Toast.makeText(this,"Signed in canceled!", LENGTH_SHORT).show();
            finish();
        }
    } else if(requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK){

        // HERE I CALLED THAT METHOD
        uploadPhotoInFirebase(data);

    }
}

private void uploadPhotoInFirebase(@Nullable Intent data) {
    Uri selectedImageUri = data.getData();

    // Get a reference to store file at chat_photos/<FILENAME>
    final StorageReference photoRef = mChatPhotoStorageReference
                    .child(selectedImageUri
                    .getLastPathSegment());

    // Upload file to Firebase Storage
    photoRef.putFile(selectedImageUri)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    // Download file From Firebase Storage
                    photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri downloadPhotoUrl) {
                            //Now play with downloadPhotoUrl
                            //Store data into Firebase Realtime Database
                            FriendlyMessage friendlyMessage = new FriendlyMessage
                                    (null, mUsername, downloadPhotoUrl.toString());
                            mDatabaseReference.push().setValue(friendlyMessage);
                        }
                    });
                }
            });
}

回答by Shrawan

here i am uploading and getting the image url at the same time...

在这里,我同时上传和获取图片网址...

           final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");

            if (uriProfileImage != null) {

            profileImageRef.putFile(uriProfileImage)
                        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                               // profileImageUrl taskSnapshot.getDownloadUrl().toString(); //this is depreciated

                          //this is the new way to do it
                   profileImageRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Uri> task) {
                                       String profileImageUrl=task.getResult().toString();
                                        Log.i("URL",profileImageUrl);
                                    }
                                });
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                progressBar.setVisibility(View.GONE);
                                Toast.makeText(ProfileActivity.this, "aaa "+e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });
            }

回答by Vikash Sharma

Clean And Simple
private void putImageInStorage(StorageReference storageReference, Uri uri, final String key) {
        storageReference.putFile(uri).addOnCompleteListener(MainActivity.this,
                new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (task.isSuccessful()) {
                            task.getResult().getMetadata().getReference().getDownloadUrl()
                                    .addOnCompleteListener(MainActivity.this, 
                                            new OnCompleteListener<Uri>() {
                                @Override
                                public void onComplete(@NonNull Task<Uri> task) {
                                    if (task.isSuccessful()) {
                                        FriendlyMessage friendlyMessage =
                                                new FriendlyMessage(null, mUsername, mPhotoUrl,
                                                        task.getResult().toString());
                                        mFirebaseDatabaseReference.child(MESSAGES_CHILD).child(key)
                                                .setValue(friendlyMessage);
                                    }
                                }
                            });
                        } else {
                            Log.w(TAG, "Image upload task was not successful.",
                                    task.getException());
                        }
                    }
                });
    }

回答by DeveLion

The getDownloadUrl method was removed in firebase versions greater than 11.0.5 I recommend using version 11.0.2 that still uses this method.

在高于 11.0.5 的 firebase 版本中删除了 getDownloadUrl 方法我建议使用仍然使用此方法的版本 11.0.2。

回答by TwistenTiger

For me, I did my code in Kotlin and I had the same error "getDownload()". Here are both the dependencies that worked for me and the Kotlin code.

对我来说,我在 Kotlin 中完成了我的代码,但我遇到了同样的错误“getDownload()”。以下是对我有用的依赖项和 Kotlin 代码。

implementation 'com.google.firebase:firebase-storage:18.1.0'firebase storage dependencies

implementation 'com.google.firebase:firebase-storage:18.1.0'Firebase 存储依赖项

This what I added and it worked for me in Kotlin. Storage() would come before Download()

这是我添加的内容,它在 Kotlin 中对我有用。Storage() 会在 Download() 之前出现

profileImageUri = taskSnapshot.storage.downloadUrl.toString()

回答by epiphmo

The getDownloadUrl method has now been depreciated in the new firebase update. Instead use the following method. taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()

getDownloadUrl 方法现已在新的 Firebase 更新中弃用。而是使用以下方法。 taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()

回答by chris

change the received URIto URL

将接收到的URI更改为URL

 val urlTask = uploadTask.continueWith { task ->
            if (!task.isSuccessful) {
                task.exception?.let {
                    throw it
                }
            }


            spcaeRef.downloadUrl
        }.addOnCompleteListener { task ->
            if (task.isSuccessful) {

                val downloadUri = task.result

                //URL
                val url = downloadUri!!.result

            } else {
                //handle failure here
            }
        }

回答by Hamza Khliefat

You can Upload images to firestore and get it's download URL as below function:

您可以将图像上传到 firestore 并获取其下载 URL,如下功能:

  Future<String> uploadPic(File _image) async {

    String fileName = basename(_image.path);
    StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
    var downloadURL = await(await uploadTask.onComplete).ref.getDownloadURL();
    var url =downloadURL.toString();

   return url;

  }