taskSnapshot.getDownloadUrl()方法不起作用

时间:2018-05-29 13:13:21

标签: android

private void uploadImageToFirebaseStorage() {
    StorageReference profileImageRef =
        FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");

    if (uriProfileImage != null) {
        progressBar.setVisibility(View.VISIBLE);
        profileImageRef.putFile(uriProfileImage)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
                    progressBar.setVisibility(View.GONE);
                    profileImageUrl = taskSnapshot.**getDownloadUrl**().toString();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(ProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
    }
}

taskSnapshot.getDownloadUrl()方法不起作用,在它下面出现红线

22 个答案:

答案 0 :(得分:32)

Firebase Storage API 16.0.1版中的

。 使用taskSnapshot对象的getDownloadUrl()方法已更改。 现在你可以使用'
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString() 从firebase存储中获取下载URL。

答案 1 :(得分:7)

要从存储获取imageUrl路径,请使用以下代码:

uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        if (taskSnapshot.getMetadata() != null) {
            if (taskSnapshot.getMetadata().getReference() != null) {
                Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
                result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String imageUrl = uri.toString();
                        //createNewPost(imageUrl);
                    }
                });
            }
        }
    }});

仅此

  

注意:不要忘记在uploadFile方法中初始化StorageReference和UploadTask。

答案 2 :(得分:4)

尝试使用它将从FireBase存储下载图像

FireBase库版本16.0.1

Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
      @Override
      public void onSuccess(Uri uri) {
             String photoStringLink = uri.toString();
      }
});

答案 3 :(得分:2)

我的Google Firebase插件位于build.gradle(模块:应用):

implementation 'com.firebaseui:firebase-ui-database:3.3.1'
implementation 'com.firebaseui:firebase-ui-auth:3.3.1'
implementation 'com.google.firebase:firebase-core:16.0.0'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-auth:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.1'

的build.gradle(项目):

 classpath 'com.google.gms:google-services:3.2.1'

我的upload()函数并从Firebase存储中获取上传的数据:

private void upload() {
    if (filePath!=null) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        final StorageReference ref = storageReference.child(new StringBuilder("images/").append(UUID.randomUUID().toString()).toString());
        uploadTask = ref.putFile(filePath);

        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();
                    progressDialog.dismiss();
                    // Continue with the task to get the download URL
                    saveUrlToCategory(downloadUri.toString(),categoryIdSelect);
                } else {
                    Toast.makeText(UploadWallpaper.this, "Fail UPLOAD", Toast.LENGTH_SHORT).show();
                }
            }
        }).addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                progressDialog.setMessage("Uploaded: ");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                progressDialog.dismiss();
                Toast.makeText(UploadWallpaper.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

对于那些使用最新火焰版本的人来说,taskSnapshot.getDownloadUrl()方法已弃用或已废弃!

答案 4 :(得分:2)

我遇到了使用此方法解决的类似错误。希望对您有帮助

uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Task<Uri> task = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                task.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String photoLink = uri.toString();
                        Map userInfo = new HashMap();
                        userInfo.put("profileImageUrl", photoLink);
                        mUserDatabase.updateChildren(userInfo);
                    }
                });
                finish();
                return;
            }
        });

答案 5 :(得分:1)

taskSnapshot.**getDownloadUrl**().toString(); //deprecated and removed

使用以下代码下载Url

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

profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
        {
            @Override
            public void onSuccess(Uri downloadUrl) 
            {                
               //do something with downloadurl
            } 
        });

答案 6 :(得分:1)

您现在不会使用

获取图像的下载网址
profileImageUrl = taskSnapshot.**getDownloadUrl**().toString();

不推荐使用此方法。

您可以使用以下方法

    uniqueId = UUID.randomUUID().toString();
    ur_firebase_reference = storageReference.child("user_photos/" + uniqueId);

    Uri file = Uri.fromFile(new File(mphotofile.getAbsolutePath()));
    UploadTask uploadTask = ur_firebase_reference.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 ur_firebase_reference.getDownloadUrl();
        }
    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
        @Override
        public void onComplete(@NonNull Task<Uri> task) {
            if (task.isSuccessful()) {
                Uri downloadUri = task.getResult();
                System.out.println("Upload " + downloadUri);
                Toast.makeText(mActivity, "Successfully uploaded", Toast.LENGTH_SHORT).show();
                if (downloadUri != null) {

                    String photoStringLink = downloadUri.toString(); //YOU WILL GET THE DOWNLOAD URL HERE !!!!
                    System.out.println("Upload " + photoStringLink);

                }

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

答案 7 :(得分:1)

//upload button onClick
public void uploadImage(View view){
    openImage()
}

private Uri imageUri;

ProgressDialog pd;

//Call open Image from any onClick Listener
private void openImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent,IMAGE_REQUEST);
}

private void uploadImage(){
    pd = new ProgressDialog(mContext);
    pd.setMessage("Uploading...");
    pd.show();

    if (imageUri != null){
        final StorageReference fileReference = storageReference.child(userID
                + "."+"jpg");

        // Get the data from an ImageView as bytes
        _profilePicture.setDrawingCacheEnabled(true);
        _profilePicture.buildDrawingCache();

        //Bitmap bitmap = ((BitmapDrawable) _profilePicture.getDrawable()).getBitmap();

        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
        } catch (IOException e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        byte[] data = baos.toByteArray();

        UploadTask uploadTask = fileReference.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle unsuccessful uploads
                pd.dismiss();
                Log.e("Data Upload: ", "Failled");
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
                // ...
                Log.e("Data Upload: ", "success");
                Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String downloadLink = uri.toString();
                        Log.e("download url : ", downloadLink);
                    }
                });

                pd.dismiss();

            }
        });

    }else {
        Toast.makeText(getApplicationContext(),"No Image Selected", Toast.LENGTH_SHORT).show();
    }
}

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

    Bitmap bitmap = null;
    if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
        imageUri = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
            _profilePicture1.setImageBitmap(bitmap);
            _profilePicture1.setDrawingCacheEnabled(true);
            _profilePicture1.buildDrawingCache();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (uploadTask != null && uploadTask.isInProgress()){
            Toast.makeText(mContext,"Upload in Progress!", Toast.LENGTH_SHORT).show();
        }
        else {
            try{
                uploadImage();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

答案 8 :(得分:1)

我正在使用Firebase Storage API 16.0.5版,该任务必须引用为

 someTask.getResult().getMetadata().getReference().getDownloadUrl().toString();

希望这会有所帮助!

答案 9 :(得分:0)

这将解决您的问题。...

if(uploadTask.isSuccessfull()){
Task<Uri> uriTask=uploadTask.getResult().getStorage().getDownloadUrl();                                               while(!uriTask.isSuccessful());
Uri downloadUri=uriTask.getResult();
final String download_url=downloadUri.toString();
}

答案 10 :(得分:0)

您还可以使用Picasso dependencies。易于在firebase中上传图片。

活动文件:

 Picasso.get().load(uriImage).into(ImageUri);

应用等级:

com.squareup.picasso:picasso:2.71828

答案 11 :(得分:0)

使用 Firebase存储版本15.0.0

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

答案 12 :(得分:0)

这有助于帮助我了解04/2020中的最后一个依赖项

     // Get a reference to store file at chat_photos/<FILENAME>
     final StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
     photoRef.putFile(selectedImageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        //When the image has successfully uploaded, get its downloadURL
                        photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                Uri dlUri = uri;
                                FriendlyMessage friendlyMessage = new 
                                  FriendlyMessage(null, mUsername, dlUri.toString());

答案 13 :(得分:0)

尝试一下:

Uri download_uri ;

final Map<String, String> userData = new HashMap<>();
    if (task != null) {
       //download_uri = task.getResult().getDownloadUrl();
      download_uri = task.getResult().getUploadSessionUri();
    }
    else {
        download_uri= imageUri;
    }

userData.put("Image", download_uri.toString());
userData.put("name",username);
userData.put("category",category);
userData.put("status",status);

答案 14 :(得分:0)

这将起作用:

.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {


                Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String photoStringLink = uri.toString();
                        Log.i("urlimage", photoStringLink);
                    }
                });
            }
        });

答案 15 :(得分:0)

//firebase database
implementation 'com.google.firebase:firebase-database:15.0.0'
//firebase storage
implementation 'com.google.firebase:firebase-storage:15.0.0'

.getDownloadUrl()方法已从更高版本中删除,我将其更改为15.0.0并可以正常使用。您可以在build.gradle(module:app)

中找到它们

答案 16 :(得分:0)

FirebaseStorage库版本 19.0.1

一起使用
String download_image_path = task.getResult().getUploadSessionUri().toString();

答案 17 :(得分:0)

 ref.putFile(filePath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                        taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                            @Override
                            public void onComplete(@NonNull Task<Uri> task) {
                                changeProfilePic(String.valueOf(task.getResult()));//gives image or file string url
                            }
                        });

尝试使用此代码肯定可以

答案 18 :(得分:0)

仅... taskSnapshot.getStorage()。getDownloadUrl();

                            Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
                        result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                String photoStringLink = uri.toString();
                                mDatavaseRef.push().setValue(photoStringLink);
                            }
                        });

答案 19 :(得分:0)

尝试使用此:

taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()

答案 20 :(得分:0)

了解最新版本

profileImageUrl = taskSnapshot.getStorage().getDownloadUrl().toString();

答案 21 :(得分:-1)

我仍然有此错误。可能是什么问题?我已经更改了权限,并将用户更改为匿名用户。

enter image description here