【问题标题】:Upload Image on Firebase Storage在 Firebase 存储上上传图片
【发布时间】:2021-06-28 10:06:02
【问题描述】:

您好,我想使用 android studio 在 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 + "%");
            }
        });
    }

【问题讨论】:

  • 您能否使用从 logcat 获得的输出更新您的回答者?如果您添加 image_uristorageReference 的来源将非常有帮助。
  • 这段代码中到底有什么不符合您的预期?告诉我们共享代码有什么问题。你有什么错误吗?请回复@AlexMamo
  • @AlexMamo 代码工作得很好,但它是 firebase 的一个问题。我更新了我的规则,但是当我查看 firebase 统计数据时,firebase 仍然拒绝我上传图片我可以看到所有我的请求被拒绝了,我不知道为什么
  • 您能告诉我们您使用的规则吗?

标签: java android firebase firebase-storage


【解决方案1】:
  • 如果你没有得到错误比较这个简单的代码
    谢谢你

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 + "%");
                            }
                        });
    }
}
}

【讨论】:

    【解决方案2】:

    我通过修改我的 firebase 规则以直接与存储桶匹配而不是与我的 firebase 存储的 ref 匹配找到了解决方案

    【讨论】:

      猜你喜欢
      • 2020-10-05
      • 2021-12-23
      • 2021-08-18
      • 2020-12-30
      • 1970-01-01
      • 2017-09-21
      • 2021-07-06
      • 2019-12-04
      相关资源
      最近更新 更多