无法在Android中的Firebase存储中上传图像

时间:2017-12-27 07:39:32

标签: android firebase firebase-realtime-database firebase-storage

我正在学习在Firebase存储中上传图片,但是当我运行/打开我的应用并选择要上传的图片时,没有任何图片可以在firebase存储中上传,请帮助我错误地编写代码。< / p>

的AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

MainActivity.java:

package com.fireapp.newfireapplication;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

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;

public class MainActivity extends AppCompatActivity {

    private StorageReference storageReference;
    private static final int GALLERY_INTENT=1;


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

        storageReference = FirebaseStorage.getInstance().getReference();
    }

    public void buttonClicked(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent,GALLERY_INTENT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == GALLERY_INTENT && requestCode == RESULT_OK){
            Uri uri = data.getData();
            StorageReference filepath = storageReference.child("Photos").child(uri.getLastPathSegment());
            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(MainActivity.this,"Image Uploaded",Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}

activity_main.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"
    android:padding="16dp"
    tools:context="com.fireapp.newfireapplication.MainActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload Image"
        android:onClick="buttonClicked"/>

</LinearLayout>

2 个答案:

答案 0 :(得分:0)

请尝试以下完整代码。

<强> 1。使用progressDialog将图像上传到Firebase。

<强> 2。缩小图像大小,然后发送到Firebase。

 uploadimage_firebase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(filePath != null) {

                    progressDialog.setCancelable(false);
                    progressDialog.show();

                    Log.d("file.getName()","***    "+filePath);
                    File file= new File(filePath.getPath());
                    file.getName();


                    /*    Compress Image file size below code     */


                    Bitmap bmp = null;
                    try {

                        bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);

                    } catch (IOException e) {

                        Log.d("PrintIOExeception","*****     "+e.toString());
                        e.printStackTrace();
                       }

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



                    //uploading the image //
                    UploadTask uploadTask = storageRef.child(file.getName()).putBytes(data);


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

                         Uri urlvalues =    taskSnapshot.getDownloadUrl();

                         Log.d("displayimageurls","****    "+urlvalues);


                            Toast.makeText(Firebase_Imageuploading.this, "Upload successful", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            progressDialog.dismiss();

                            Log.d("printimaguploadfaild","*****    "+e.toString());

                            Toast.makeText(Firebase_Imageuploading.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
                        }
                    }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            //calculating progress percentage
                            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();

                            //displaying percentage in progress dialog
                            progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                        }
                    });
                }
                else {
                    Toast.makeText(Firebase_Imageuploading.this, "Select an image", Toast.LENGTH_SHORT).show();
                }

            }
        });

答案 1 :(得分:0)

尝试Firebase Helper Class

 progressDialog.setMessage(context.getString(R.string.loading));
            progressDialog.show();


       filePath = mFStorage.child("image").child(getRandomId() + ".png");

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

                progressDialog.dismiss();

                imageUrl = taskSnapshot.getDownloadUrl().toString();


            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                progressDialog.dismiss();
                //Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                //displaying the upload progress
                double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
            }
        });