将多个图像上传到Firebase存储中

问题描述 投票:1回答:2

我使用Firebase构建聊天应用程序,并且我想将多个图像发送到Firebase存储。

使用此库

编译'com.github.darsh2:MultipleImageSelect:3474549'

在顶部

private StorageReference storageRef;
private FirebaseApp app;
private FirebaseStorage storage;

onCreate()方法

app = FirebaseApp.getInstance();
storage =FirebaseStorage.getInstance(app);

按钮单击动作

   Gallary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Intent intent = new Intent(ChatActivity.this, AlbumSelectActivity.class);
                intent.putExtra(Constants.INTENT_EXTRA_LIMIT, 10);
                startActivityForResult(intent, Constants.REQUEST_CODE);
                pwindo1.dismiss();
            }
        });

活动结果

    if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK) {
        ArrayList<Image> images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
        Uri uri = Uri.parse(String.valueOf(images));
        storageRef = storage.getReference("photos");
        final StorageReference photoRef = storageRef.child(uri.getLastPathSegment());
        photoRef.putFile(uri)
                .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();
                        String content = downloadUrl.toString();
                        if (content.length() > 0) {
                            editWriteMessage.setText("");
                            Message newMessage = new Message();
                            newMessage.text = content;
                            newMessage.idSender = StaticConfig.UID;
                            newMessage.idReceiver = roomId;
                            newMessage.timestamp = System.currentTimeMillis();
                            FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage);
                        }
                    }
                });

    }
android firebase firebase-storage
2个回答
4
投票

工作正常。

 if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK) {
        ArrayList<Image> images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
        Uri[] uri=new Uri[images.size()];
        for (int i =0 ; i < images.size(); i++) {
            uri[i] = Uri.parse("file://"+images.get(i).path);
            storageRef = storage.getReference("photos");
            final StorageReference ref = storageRef.child(uri[i].getLastPathSegment());
            ref.putFile(uri[i])
                    .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Uri downloadUrl = taskSnapshot.getDownloadUrl();
                            String content = downloadUrl.toString();
                            if (content.length() > 0) {
                                editWriteMessage.setText("");
                                Message newMessage = new Message();
                                newMessage.text = content;
                                newMessage.idSender = StaticConfig.UID;
                                newMessage.idReceiver = roomId;
                                newMessage.timestamp = System.currentTimeMillis();
                                FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage);
                            }
                        }
                    });

        }

    }

0
投票

还需要有关如何将多个图像上传到Firebase存储的帮助

public class RoadUpload extends AppCompatActivity
{
    private Toolbar mToolbar;
    private ProgressDialog loadingBar;

    private ImageButton SelectPostImage;
    private Button UpdatePostButton;
    private EditText PostDescription,PostDescription1;

    private static final int Gallery_Pick = 1;
    private Uri ImageUri;
    private String Description;
    private String Description1;
    private String myphone,myprice;
    private Spinner myspinner;

    private StorageReference PostsImagesRefrence;
    private DatabaseReference UsersRef, PostsRef;
    private FirebaseAuth mAuth;
    private String saveCurrentDate, saveCurrentTime, postRandomName, downloadUrl, current_user_id;
    private int  countposts = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_road_upload);

        mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("Upload Road Issues");
        mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        mAuth = FirebaseAuth.getInstance();
        current_user_id = mAuth.getCurrentUser().getUid();

        PostsImagesRefrence = FirebaseStorage.getInstance().getReference();
        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
        PostsRef = FirebaseDatabase.getInstance().getReference().child("roads");


        SelectPostImage = (ImageButton) findViewById(R.id.imageButton);
        UpdatePostButton = (Button) findViewById(R.id.update_post_button);
        PostDescription =(EditText) findViewById(R.id.post_description);
        PostDescription1 =(EditText) findViewById(R.id.post_description1);
        loadingBar = new ProgressDialog(this);

/*
        mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
        setSupportActionBar(mToolbar);
        //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Post New Product");
*/



        SelectPostImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                OpenGallery();
            }
        });


        UpdatePostButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                ValidatePostInfo();
            }
        });
    }



    private void ValidatePostInfo()
    {
        Description = PostDescription.getText().toString();
        Description1 = PostDescription1.getText().toString();
        if(ImageUri == null)
        {
            Toast.makeText(this, "Please select post image...", Toast.LENGTH_SHORT).show();
        }else if(TextUtils.isEmpty(Description))
        {
            Toast.makeText(this, "Please say something about your product...", Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(Description1))
        {
            Toast.makeText(this, "Please state your location...", Toast.LENGTH_SHORT).show();
        }
        else
        {
            loadingBar.setTitle("Add New Post");
            loadingBar.setMessage("Please wait, while we are updating your new post...");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);

            StoringImageToFirebaseStorage();
        }
    }



    private void StoringImageToFirebaseStorage()
    {
        Calendar calFordDate = Calendar.getInstance();
        SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
        saveCurrentDate = currentDate.format(calFordDate.getTime());

        Calendar calFordTime = Calendar.getInstance();
        SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
        saveCurrentTime = currentTime.format(calFordDate.getTime());

        postRandomName = saveCurrentDate + saveCurrentTime;


        StorageReference filePath = PostsImagesRefrence.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg" + ".png" + ".gif" + ".mp3" + ".mp4" + ".pdf" + ".doc" + ".xls" + ".xlsx");

        filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
            {
                if(task.isSuccessful())
                {
                    downloadUrl = task.getResult().getDownloadUrl().toString();
                    Toast.makeText(RoadUpload.this, "image uploaded successfully...", Toast.LENGTH_SHORT).show();

                    SavingPostInformationToDatabase();

                }
                else
                {
                    String message = task.getException().getMessage();
                    Toast.makeText(RoadUpload.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }




    private void SavingPostInformationToDatabase()
    {
        PostsRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()){
                    countposts= (int) dataSnapshot.getChildrenCount();

                }else {

                    countposts = 0;
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot)
            {
                if(dataSnapshot.exists())
                {
                    String userFullName = dataSnapshot.child("fullname").getValue().toString();
                    String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();

                    HashMap postsMap = new HashMap();
                    postsMap.put("uid", current_user_id);
                    postsMap.put("location", saveCurrentTime);
                    postsMap.put("date", saveCurrentDate);
                    postsMap.put("time", saveCurrentTime);
                    postsMap.put("description", Description);
                    postsMap.put("description1", Description1);
                    //postsMap.put("phone", myphone);
                    //postsMap.put("price", myprice);
                    postsMap.put("counter", countposts);
                    postsMap.put("postimage", downloadUrl);
                    postsMap.put("profileimage", userProfileImage);
                    postsMap.put("fullname", userFullName);
                    PostsRef.child(current_user_id + postRandomName).updateChildren(postsMap)
                            .addOnCompleteListener(new OnCompleteListener() {
                                @Override
                                public void onComplete(@NonNull Task task)
                                {
                                    if(task.isSuccessful())
                                    {
                                        SendUserToMainActivity();
                                        Toast.makeText(RoadUpload.this, "New Post is updated successfully.", Toast.LENGTH_SHORT).show();
                                        loadingBar.dismiss();
                                    }
                                    else
                                    {
                                        Toast.makeText(RoadUpload.this, "Error Occured while updating your post.", Toast.LENGTH_SHORT).show();
                                        loadingBar.dismiss();
                                    }
                                }
                            });
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }



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



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

        if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
        {
            ImageUri = data.getData();
            SelectPostImage.setImageURI(ImageUri);
        }
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();

        if(id == android.R.id.home)
        {
            SendUserToMainActivity();
        }

        return super.onOptionsItemSelected(item);
    }



    private void SendUserToMainActivity()
    {
        Intent mainIntent = new Intent(RoadUpload.this, MainActivity.class);
        startActivity(mainIntent);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.