如何从 Firebase 存储获取 URL getDownloadURL

How to get URL from Firebase Storage getDownloadURL

我正在尝试获取 "long term persistent download link" 到我们的 Firebase 存储桶中的文件。 我已将其权限更改为

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

我的 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;
}

当我 运行 这个时,我得到的 uri link 看起来像 com.google.android.gms.tasks.zzh@xxx

问题1.我可以从这里下载link类似于:https://firebasestorage.googleapis.com/v0/b/project-xxxx.appspot.com/o/20-5-2016.csv?alt=media&token=b5d45a7f-3ab7-4f9b-b661-3a2187adxxxx

在尝试获取上面的 link 时,我更改了 return 之前的最后一行,如下所示:

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;
}

但是在执行此操作时出现 403 错误,并且应用程序崩溃了。 consol 告诉我这是 bc 用户未登录 /auth。 "Please sign in before asking for token"

问题 2。我该如何解决?

请参考documentation for getting a download URL.

当您调用 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
        } 
    });
}

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

但是,如果您想要的只是引用的 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();
}
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
            }
       }
});

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

@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);
                        }
                    });
                }
            });
}

这里我正在上传并同时获取图片url...

           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();
                            }
                        });
            }
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());
                        }
                    }
                });
    }

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

对我来说,我在 Kotlin 中编写代码时遇到了同样的错误 "getDownload()"。这是对我有用的依赖项和 Kotlin 代码。

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

这是我添加的,它在 Kotlin 中对我有用。 Storage() 会先于 Download()

profileImageUri = taskSnapshot.storage.downloadUrl.toString()

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

将收到的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
            }
        }

您可以将图片上传到 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;

  }

看这个 https://www.youtube.com/watch?v=SsF8i4WiZpU

对我有用!!!

代码: https://github.com/augustina55/firebaseupload

 private void getDownloadUrl(){
        FirebaseStorage storage     = FirebaseStorage.getInstance();
        StorageReference storageRef = storage.getReference();
        StorageReference imageRef   = storageRef.child("image.jpg");
        imageRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                String profileimageurl =task.getResult().toString();
                Log.e("URL",profileimageurl);
                ShowPathTextView.setText(profileimageurl);
            }
        });
    }

你也可以按照下面的方式做在最新的Firebase_storage版本nullsafe中,

//Import
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;

Future<void> _downloadLink(firebase_storage.Reference ref) async {
    //Getting link make sure call await to make sure this function returned a value
    final link = await ref.getDownloadURL();

    await Clipboard.setData(ClipboardData(
      text: link,
    ));

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text(
          'Success!\n Copied download URL to Clipboard!',
        ),
      ),
    );
  }
implementation 'com.google.firebase:firebase-storage:19.2.0'

最近从上传任务中获取 url 无效,所以我尝试了这个并在上述依赖项上为我工作。 所以在你使用 firebase 上传方法的地方使用这个。 filepath 是 Firebase Stoarage 的引用。

filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                Log.d(TAG, "onSuccess: uri= "+ uri.toString());
            }
        });
    }
});