如何将多个图像上传到Firebase的实时数据库?

时间:2019-01-14 03:39:06

标签: java android firebase firebase-realtime-database

enter image description here

我想将多个图像上传到Firebase的实时数据库。它只能处理单个图像,但不能处理多个图像。

我知道我必须为每个单独的图像指定不同的路径,但是我不知道该怎么做。

有人可以帮助我更改代码,或者至少指导我解决问题吗?我在网上搜索了答案的资源,但尚未找到答案。预先感谢!

如何基于代码将多个图像上传到Firebase的实时数据库中,我需要集成/实现什么?

package com.amazoneindia.amazone_india;


import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.FileNotFoundException;
import java.io.IOException;

import static android.app.Activity.RESULT_OK;


/**
 * A simple {@link Fragment} subclass.
 */
public class Upload_apk extends Fragment {
    Button bt1,bt2;
    TextView tv;
    Button btnss1,btnss2,btnss3,btnss4,btnss5;
    TextView tvss1,tvss2,tvss3,tvss4,tvss5;
    private EditText Name, Email, Pass, Ph, AppTitle, Appdescript;
    private FirebaseAuth mAuth;
    private StorageReference mStorageRef;
    private DatabaseReference mDatabaseRef;
    private ImageView imageView;
    private ImageView imagess1,imagess2,imagess3,imagess4,imagess5;
    private Uri imageUri;


    public static final String FB_STORAGE_PATH = "image/";
    public static final String FB_DATABASE_PATH = "image";
    public static final int REQUEST_CODE=1234;




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_upload_apk, container, false);
        mStorageRef = FirebaseStorage.getInstance().getReference();
        mDatabaseRef = FirebaseDatabase.getInstance().getReference(FB_DATABASE_PATH);


        imageView = view.findViewById(R.id.etimage);
        imagess1=view.findViewById(R.id.imagess1);
        imagess2=view.findViewById(R.id.imagess2);
        imagess3=view.findViewById(R.id.imagess3);
        imagess4=view.findViewById(R.id.imagess4);
        imagess5=view.findViewById(R.id.imagess5);
        Name = view.findViewById(R.id.etname);
        Email = view.findViewById(R.id.etemail);
        Pass = view.findViewById(R.id.etpassword);
        Ph = view.findViewById(R.id.etphone);
        AppTitle=view.findViewById(R.id.ettitle);
        Appdescript=view.findViewById(R.id.etdescrip);
        tv=view.findViewById(R.id.upload_tv);
        tvss1=view.findViewById(R.id.tvss1);
        tvss2=view.findViewById(R.id.tvss2);
        tvss3=view.findViewById(R.id.tvss3);
        tvss4=view.findViewById(R.id.tvss4);
        tvss5=view.findViewById(R.id.tvss5);
        bt1=view.findViewById(R.id.browsebtn);
        btnss1=view.findViewById(R.id.btnss1);
        btnss2=view.findViewById(R.id.btnss2);
        btnss3=view.findViewById(R.id.btnss3);
        btnss4=view.findViewById(R.id.btnss4);
        btnss5=view.findViewById(R.id.btnss5);
        bt2=view.findViewById(R.id.upload_btn);

        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
            }
        });
        btnss1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
            }
        });
        btnss2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
            }
        });
        btnss3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
            }
        });
        btnss4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
            }
        });
        btnss5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imageUri!=null){
                    final ProgressDialog dialog=new ProgressDialog(getContext());
                    dialog.setTitle("Uploading Image....");
                    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    dialog.setProgress(0);
                    dialog.show();
                    bt1.setVisibility(View.GONE);
                    tv.setVisibility(View.GONE);
                    btnss1.setVisibility(View.GONE);
                    tvss1.setVisibility(View.GONE);
                    btnss2.setVisibility(View.GONE);
                    tvss2.setVisibility(View.GONE);
                    btnss3.setVisibility(View.GONE);
                    tvss3.setVisibility(View.GONE);
                    btnss4.setVisibility(View.GONE);
                    tvss4.setVisibility(View.GONE);
                    btnss5.setVisibility(View.GONE);
                    tvss5.setVisibility(View.GONE);

                    StorageReference ref =mStorageRef.child(FB_STORAGE_PATH + System.currentTimeMillis() +"."+getImageExt(imageUri));
                    ref.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {


                            dialog.dismiss();
                            Toast.makeText(getActivity(),"Image Uploaded",Toast.LENGTH_SHORT).show();
                            ImageUpload imageUpload=new ImageUpload(Name.getText().toString(),Email.getText().toString(),Pass.getText().toString(),Ph.getText().toString(),AppTitle.getText().toString(),Appdescript.getText().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
                            String uploaded=mDatabaseRef.push().getKey();
                            mDatabaseRef.child(uploaded).setValue(imageUpload);
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {

                            dialog.dismiss();
                            Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
                        }
                    }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            int progress=(int)(100 * taskSnapshot.getBytesTransferred()/ taskSnapshot.getTotalByteCount());
                            dialog.setProgress(progress);
                        }
                    });
                }else {
                    Toast.makeText(getActivity(),"Please select image",Toast.LENGTH_SHORT).show();
                }
            }
        });
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQUEST_CODE && resultCode == RESULT_OK && data !=null && data.getData() != null){
            imageUri=data.getData();
            try{
                Bitmap bm= MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),imageUri);
                imageView.setImageBitmap(bm);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getImageExt(Uri uri){
        ContentResolver contentResolver=getActivity().getContentResolver();
        MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
        return  mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
    }
}

2 个答案:

答案 0 :(得分:0)

将选择的图像保存在位图列表中

bitmaps[i] = MediaStore.Images.Media.getBitmap(getContentResolver(), fileList[i]);

将多张图片上传到Firebase的方法

private void uploadImages() {

    if (filePath != null) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        uri = new Uri[bitmaps.length];
        for (int i = 0; i < bitmaps.length; i++) {
            if (bitmaps[i] == null) {
                break;
            } else {
                uri[i] = getImageUri(this, bitmaps[i]);
                Log.e("ImageUploadActivity", "---///" + i + "--" + 
        uri[i].toString());

                mStorageReferenceImages = storageReference.child("images");

                StorageReference ref = 
 mStorageReferenceImages.child(uri[i].getLastPathSegment());
                ref.putFile(uri[i])
                        .addOnSuccessListener(new 
 OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot 
 taskSnapshot)
                            {
                                progressDialog.dismiss();
                                Toast.makeText(ImageUploadActivity.this, "Uploaded", 
 Toast.LENGTH_SHORT).show();
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                progressDialog.dismiss();
                                Toast.makeText(ImageUploadActivity.this, "Failed " + 
 e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        })
                        .addOnProgressListener(new 
 OnProgressListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onProgress(UploadTask.TaskSnapshot 
 taskSnapshot) {
                                double progress = (100.0 * 
taskSnapshot.getBytesTransferred() / taskSnapshot
                                        .getTotalByteCount());
                                progressDialog.setMessage("Uploaded " + (int) 
    progress + "%");
                            }
                        });
            }

        }
    }
}

将位图转换为uri的方法

 /*--convert bitmap to uri--*/
public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), 
inImage, "Title", null);
    return Uri.parse(path);
}

答案 1 :(得分:0)

您可以为所有image_screenshots添加复选框,然后在按下opload按钮时 进行逻辑运算以找出选中了哪个复选框,并据此可以上传屏幕截图,例如逻辑-> btn上载时,按添加if语句检查复选框的条件,如果要保留3个屏幕快照,则添加3个单独的内容

on Button pressed{
 if(checkbox1.isChecked()) { uploadimage}
 if(checkbox2.isChecked()) { uploadimage}
 if(checkbox3.isChecked()) { uploadimage}
}