簡體   English   中英

在 Firebase 存儲上上傳圖像

[英]Upload Image on Firebase Storage

嗨,我想用 android 工作室在 firebase 存儲上添加圖像,但 firebase 不接受我的上傳。 我更改了規則以允許寫入和讀取,並且我的匹配文件夾允許所有路徑。因此我很困惑。 這是我的代碼中應該將圖像放入我的數據庫的部分。 如果您知道如何解決此問題,我將很高興聽到解決方案

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
            image_uri = data.getData();
            uploadPicture();
            ProfileImage.setImageURI(image_uri);

        }
    }
private void uploadPicture() {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setTitle("Uploading Image...");
        pd.show();
        final String randomKey = UUID.randomUUID().toString();
        StorageReference riversRef = storageReference.child(("images/" + randomKey + ".jpg"));


        Toast.makeText(Create_Profile.this, "Upload success", Toast.LENGTH_SHORT).show();

        riversRef.putFile(image_uri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        pd.dismiss();
                        name = riversRef.getDownloadUrl().toString();
                    }
                }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
                double progressPercent = (100.00 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
                pd.setMessage("Percentage: " + (int) progressPercent + "%");
            }
        });
    }
  • 如果你沒有得到錯誤與這個簡單的代碼比較
    謝謝你

firebase 存儲依賴

implementation 'com.google.firebase:firebase-storage:19.1.0'

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<!--Linear Layout with horizontal orientation
and other properties-->
<LinearLayout
android:id="@+id/layout_button"
android:orientation="horizontal"
android:layout_alignParentTop="true"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<!--Button for choosing image from gallery-->
<Button
    android:id="@+id/btnChoose"
    android:text="Choose"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content" />

<!--Button for uploading image-->
<Button
    android:id="@+id/btnUpload"
    android:text="Upload"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content" />
</LinearLayout>

<!--Image View for showing image choosen from gallery-->
<ImageView
    android:id="@+id/imgView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</RelativeLayout>

在您的活動中

public class MainActivity extends AppCompatActivity {

private Button btnSelect, btnUpload;
private ImageView imageView;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 22;
FirebaseStorage storage;
StorageReference storageReference;

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

    ActionBar actionBar;
    actionBar = getSupportActionBar();
    ColorDrawable colorDrawable
            = new ColorDrawable(
            Color.parseColor("#0F9D58"));
    actionBar.setBackgroundDrawable(colorDrawable);


    btnSelect = findViewById(R.id.btnChoose);
    btnUpload = findViewById(R.id.btnUpload);
    imageView = findViewById(R.id.imgView);
    storage = FirebaseStorage.getInstance();
    storageReference = storage.getReference();

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

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

private void SelectImage()
{

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(
            Intent.createChooser(
                    intent,
                    "Select Image from here..."),
            PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode,
                                int resultCode,
                                Intent data)
{

    super.onActivityResult(requestCode,
            resultCode,
            data);
    if (requestCode == PICK_IMAGE_REQUEST
            && resultCode == RESULT_OK
            && data != null
            && data.getData() != null) {

        // Get the Uri of data
        filePath = data.getData();
        try {

            Bitmap bitmap = MediaStore
                    .Images
                    .Media
                    .getBitmap(
                            getContentResolver(),
                            filePath);
            imageView.setImageBitmap(bitmap);
        }

        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void uploadImage()
{
    if (filePath != null) {

        ProgressDialog progressDialog
                = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        StorageReference ref
                = storageReference
                .child(
                        "images/"
                                + UUID.randomUUID().toString());

        ref.putFile(filePath)
                .addOnSuccessListener(
                        new OnSuccessListener<UploadTask.TaskSnapshot>() {

                            @Override
                            public void onSuccess(
                                    UploadTask.TaskSnapshot taskSnapshot)
                            {

                                progressDialog.dismiss();
                                Toast
                                        .makeText(MainActivity.this,
                                                "Image Uploaded!!",
                                                Toast.LENGTH_SHORT)
                                        .show();
                            }
                        })

                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e)
                    {

                        progressDialog.dismiss();
                        Toast
                                .makeText(MainActivity.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 + "%");
                            }
                        });
    }
}
}

我通過修改我的 firebase 規則以直接與存儲桶匹配而不是與我的 firebase 存儲的引用找到了解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM