无法将图像从ImageView上传到Android中的FireBase存储

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法将图像从ImageView上传到Android中的FireBase存储相关的知识,希望对你有一定的参考价值。

在我的应用程序中,我有一个ImageView,我想将与该imageView相关联的图像保存到Firebase存储。这就是我所做的:

imageview.setDrawingCacheEnabled(true);
                imageview.buildDrawingCache();
                Bitmap bitmap = ((BitmapDrawable) imageview.getDrawable()).getBitmap();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] data = baos.toByteArray();


StorageReference mStorage;
//CURRENT_USER,CCC,CAPITAL,TYPE are strings.
mStorage = FirebaseStorage.getInstance().getReference().child(CCC).child(Case+"/"+CAPITAL+"_"+TYPE.replaceAll(" ","_")+"_front.jpg");

mStorage.putBytes(data).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                        //return null;
                        if (!task.isSuccessful()) {
                            throw task.getException();
                        }
                        return mStorage.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()) {
                            Uri downloadUri = task.getResult();
                            Log.d("save_document",downloadUri.toString());                                
                        } else {
                            Log.d("save_document","failed to upload image");
                        }
                    }
                }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d("save_document","Exception while uploading the image"+e.toString());
                }
            });

图像永远不会上传到Firebase存储中,并且日志语句也永远不会被执行,我哪里出错了?

答案

试试这个,

    StorageReference storageReference = storage.getReference();
                storageReference.child("profileImageUrl").child(userID).putFile(resultUri)
                        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                                String url = taskSnapshot.getDownloadUrl().toString();
                                mCustomerDatabase1.child("profileImageUrl").setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {


                                        if (task.isSuccessful()){
                                    Toast.makeText(getApplicationContext(),"File Successfully Uploaded",LENGTH_SHORT).show();
 }
                                        else{

                                            Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show(); }
                                    }
                                });
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {

                        Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show();

                    }
                });
另一答案

试试这个。这是我的一个项目的一段代码。我希望它有所帮助。

private static final int Gallery_Pick_Fin = 1;
private Uri ImageUriFin;
ImageView addFinImg;
private String downloadUrlFin;

protected void onCreate(Bundle savedInstanceState) {

        addFinImg = (ImageView)findViewById(R.id.add_cmnt_img);

        addFinImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        openGalleryFin();
                    }
                });

        postRecipe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressDialog.setMessage("Posting... 
 Please Wait.. :)");
                progressDialog.show();
                    final StorageReference filePath = postFinPicsRef.child("postFinPics").child(ImageUriFin.getLastPathSegment() + user.getUid());
                    filePath.putFile(ImageUriFin).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                            if (task.isSuccessful()) {
                                progressDialog.dismiss();
                                downloadUrlFin = task.getResult().getDownloadUrl().toString();
                                dbRefUser = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid());

                                dbRefUser.addListenerForSingleValueEvent(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {

                                        HashMap<String, Object> userPosts = new HashMap<>();
                                        userPosts.put("FinPic", downloadUrlFin);


                                        dbRefPost.child(user.getUid()).child("" + aa).updateChildren(userPosts);
                                        dbRefPostAll.child("Veg").child("" + aa).updateChildren(userPosts);
                                        startActivity(new Intent(getApplicationContext(), PostTabActivity.class));
                                    }

                                    @Override
                                    public void onCancelled(DatabaseError databaseError) {
                                    }
                                });
                            }
                        }
                    });

            }
        });


    }


private void openGalleryFin() {
    Intent galleryIntent = new Intent();
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    galleryIntent.setType("image/*");
    startActivityForResult(galleryIntent,Gallery_Pick_Fin);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == Gallery_Pick_Fin && resultCode == RESULT_OK && data!=null){
        ImageUriFin = data.getData();
        addFinImg.setImageURI(ImageUriFin);
    }
}

以上是关于无法将图像从ImageView上传到Android中的FireBase存储的主要内容,如果未能解决你的问题,请参考以下文章

Android Lollipop 问题 - 无法将图像从相机加载到 ImageView

Android imageview从缩放图像中获取像素颜色

将相机图像上传到 Firebase

Android:无法从mysql数据库中检索图像URL并将其显示在imageView中

Android - 在显示进度时将图像从 URL 加载到 ImageView(不保存图像)

在未找到android studio照片中将图像上传到网站