无法将图像第二次存储到firebase存储中

时间:2018-02-13 15:44:15

标签: android firebase firebase-storage

我创建了一个简单的应用程序,用户可以在其中浏览他/她的图库,在选择用于裁剪图像的图像选项后,我使用了GitHub上提供的一些图像裁剪库。 一切正常我能够裁剪图像并在图像出现在火基存储中后上传它,但是当我尝试使用不同的图像第二次上传图像时它不会上传到firebase存储中并且只显示第一个上传的图像。请帮助我任何人使用此代码执行某些操作,以便它可以上传多个图像

MainActivity.java的XML布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="imgcrop.example.com.androidimagecrop.MainActivity">

    <ImageButton
        android:id="@+id/imageview"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:background="#FFFFFF"
        android:scaleType="centerCrop"
        android:src="@android:drawable/ic_menu_report_image"
        android:visibility="visible" />

    <Button
        android:id="@+id/uploadbutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="UPLOAD IMAGE"
        android:layout_marginTop="10dp"
        />
</LinearLayout>

MainActivity.java

package imgcrop.example.com.androidimagecrop;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import com.firebase.client.Firebase;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity {

    private ImageButton imageButton;
    private Button uploadButton;
    private  static  final  int Image_request=1;
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl("gs://androidimagecrop.appspot.com");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Firebase.setAndroidContext(this);
        //getting the reference of the views
        imageButton = (ImageButton) findViewById(R.id.imageview);
        uploadButton = (Button) findViewById(R.id.uploadbutton);
        onImageViewClick(); // for selecting an Image from gallery.
        onUploadButtonClick(); // for uploading the image to Firebase Storage.
    }

    protected  void onImageViewClick(){
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent  .setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent,Image_request );
            }
        });

    }
    protected  void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == Image_request && resultCode == RESULT_OK){
                Uri selectedImageUri = data.getData();
            CropImage.activity(selectedImageUri)
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setAspectRatio(1, 1)
                    .start(this);
                if (null != selectedImageUri) {
                    // Get the path from the Uri
                    String path = getPathFromURI(selectedImageUri);
                    imageButton.setImageURI(selectedImageUri);

                }

        }
        if (requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
        {
            CropImage.ActivityResult result= CropImage.getActivityResult(data);
            if(resultCode==RESULT_OK)
            {
               Uri resulturi=result.getUri();
                imageButton.setImageURI(resulturi);
                StorageReference filepath=  storageRef.child(resulturi.getLastPathSegment());
            }
            else
            {
                if(resultCode==CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
                {
                    Exception error=result.getError();
                }
            }
        }
    }
    private String getPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

    protected void onUploadButtonClick(){

        uploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 storageRef = FirebaseStorage.getInstance().getReference().child("Profiles/image");

                imageButton.setDrawingCacheEnabled(true);
                imageButton.buildDrawingCache();
                Bitmap bitmap = imageButton.getDrawingCache();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] data = baos.toByteArray();

                UploadTask uploadTask = storageRef.putBytes(data);
                uploadTask.addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        Toast.makeText(MainActivity.this, "TASK FAILED", Toast.LENGTH_SHORT).show();
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Toast.makeText(MainActivity.this, "Image Uploaded SucessFully", Toast.LENGTH_SHORT).show();
                        Uri downloadUrl =taskSnapshot.getDownloadUrl();
                        String DOWNLOAD_URL = downloadUrl.getPath();

                    }
                });
            }
        });

    }
}

但是在更改onUploadButtonClick()方法中的子引用名称时,我能够存储不同的图像 enter image description here

这是我的firebase存储部分。我创建了一个根文件夹,在该文件夹下应存储所有图像 root folder

images

1 个答案:

答案 0 :(得分:0)

替换 storageRef = FirebaseStorage.getInstance().getReference().child("Profiles/image"); 替换storageRef = FirebaseStorage.getInstance().getReference().child("Profiles/"+System.currentTimeMillis());