简体   繁体   English

为什么图像没有上传到 Firebase 存储和craching?

[英]Why is the image not uploading to the Firebase-storage and craching?

I made an application that makes a list of people that contains (name, age, description and photo), but the problem is when I record the data in a file (AddPerson) and save it, the app craching我制作了一个包含(姓名、年龄、描述和照片)的人员列表的应用程序,但问题是当我将数据记录在文件(AddPerson)中并保存时,应用程序崩溃

this is the crash log:这是崩溃日志:

E/StorageException: StorageException has occurred.
    User does not have permission to access this object.
     Code: -13021 HttpResult: 403
E/StorageException: The server has terminated the upload session
    java.io.IOException: The server has terminated the upload session
        at com.google.firebase.storage.UploadTask.serverStateValid(UploadTask.java:339)
        at com.google.firebase.storage.UploadTask.shouldContinue(UploadTask.java:308)
        at com.google.firebase.storage.UploadTask.run(UploadTask.java:229)
        at com.google.firebase.storage.StorageTask.lambda$getRunnable$7$com-google-firebase-storage-StorageTask(StorageTask.java:1072)
        at com.google.firebase.storage.StorageTask$$ExternalSyntheticLambda3.run(Unknown Source:2)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)
     Caused by: java.io.IOException: {  "error": {    "code": 403,    "message": "Permission denied."  }}
        at com.google.firebase.storage.network.NetworkRequest.parseResponse(NetworkRequest.java:445)
        at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(NetworkRequest.java:462)
        at com.google.firebase.storage.network.NetworkRequest.processResponseStream(NetworkRequest.java:453)
        at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:272)
        at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:289)
        at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:76)
        at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:68)
        at com.google.firebase.storage.UploadTask.sendWithRetry(UploadTask.java:477)
        at com.google.firebase.storage.UploadTask.beginResumableUpload(UploadTask.java:276)
        at com.google.firebase.storage.UploadTask.run(UploadTask.java:224)
        at com.google.firebase.storage.StorageTask.lambda$getRunnable$7$com-google-firebase-storage-StorageTask(StorageTask.java:1072) 
        at com.google.firebase.storage.StorageTask$$ExternalSyntheticLambda3.run(Unknown Source:2) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
        at java.lang.Thread.run(Thread.java:923) 
    StorageException has occurred.
    User does not have permission to access this object.
     Code: -13021 HttpResult: 403
E/StorageException: The server has terminated the upload session
    java.io.IOException: The server has terminated the upload session
        at com.google.firebase.storage.UploadTask.serverStateValid(UploadTask.java:339)
        at com.google.firebase.storage.UploadTask.shouldContinue(UploadTask.java:308)
        at com.google.firebase.storage.UploadTask.run(UploadTask.java:229)
        at com.google.firebase.storage.StorageTask.lambda$getRunnable$7$com-google-firebase-storage-StorageTask(StorageTask.java:1072)
        at com.google.firebase.storage.StorageTask$$ExternalSyntheticLambda3.run(Unknown Source:2)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)
     Caused by: java.io.IOException: {  "error": {    "code": 403,    "message": "Permission denied."  }}
        at com.google.firebase.storage.network.NetworkRequest.parseResponse(NetworkRequest.java:445)
        at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(NetworkRequest.java:462)
        at com.google.firebase.storage.network.NetworkRequest.processResponseStream(NetworkRequest.java:453)
        at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:272)
        at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:289)
        at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:76)
        at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:68)
        at com.google.firebase.storage.UploadTask.sendWithRetry(UploadTask.java:477)
        at com.google.firebase.storage.UploadTask.beginResumableUpload(UploadTask.java:276)
        at com.google.firebase.storage.UploadTask.run(UploadTask.java:224)
        at com.google.firebase.storage.StorageTask.lambda$getRunnable$7$com-google-firebase-storage-StorageTask(StorageTask.java:1072) 
        at com.google.firebase.storage.StorageTask$$ExternalSyntheticLambda3.run(Unknown Source:2) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
        at java.lang.Thread.run(Thread.java:923) 

this is codes for AddPerson :这是AddPerson代码:

public class AddPersonextends AppCompatActivity {

    private TextInputEditText mFirstName, mLastName, mAge, mDescription;

    private String firstNameString, lastNameString, ageString, descriptionString;
    private Uri imageUri = null;

    CardView mInsertImage;
    ImageView mImageView;

    private static final int IMAGE_PICK_CODE = 1000;

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

        mFirstName = findViewById(R.id.first_name_input);
        mLastName = findViewById(R.id.last_name_input);
        AboutMissingSpinner = findViewById(R.id.spinner_about_missing);
        mAge = findViewById(R.id.age_input);
        mDescription = findViewById(R.id.description_input);

        mInsertImage = findViewById(R.id.insert_image);
        mImageView = findViewById(R.id.imageView);


        mInsertImage.setOnClickListener(v -> pickImageFromGallery());
    }

    private void pickImageFromGallery() {
        Intent i = new Intent();
        i.setType("image/*");
        i.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(i, IMAGE_PICK_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE) {
            assert data != null;
            imageUri = data.getData();
            mImageView.setImageURI(data.getData());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void insertPerson() {
        firstNameString = Objects.requireNonNull(mFirstName.getText()).toString().trim();
        lastNameString = Objects.requireNonNull(mLastName.getText()).toString().trim();
        ageString = Objects.requireNonNull(mAge.getText()).toString().trim();
        descriptionString = Objects.requireNonNull(mDescription.getText()).toString().trim();

        if (TextUtils.isEmpty(lastNameString)) {
            lastNameString = "";
        }

        if (TextUtils.isEmpty(firstNameString) && TextUtils.isEmpty(lastNameString)
                && TextUtils.isEmpty(ageString) && TextUtils.isEmpty(descriptionString)) {
            return;
        }

        uploadImage();
    }

    private void uploadImage() {
        long timestamp = System.currentTimeMillis();
        String filePathAndName = "images/" + timestamp;

        StorageReference storageReference = FirebaseStorage.getInstance().getReference(filePathAndName);
        storageReference.putFile(imageUri)
                .addOnSuccessListener(taskSnapshot -> {
                    Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
                    while (!uriTask.isSuccessful());
                    String uploadedImageUri = "" + uriTask.getResult();
                    sendList(uploadedImageUri, timestamp);
                }).addOnFailureListener(e -> {

                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_add_person, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_save) {
            insertPerson();
            finish();
            return true;
        } else if (item.getItemId() == android.R.id.home) {
            if (TextUtils.isEmpty(firstNameString) && TextUtils.isEmpty(lastNameString)
                    && TextUtils.isEmpty(ageString) && TextUtils.isEmpty(descriptionString)) {
            }

            showUnsavedChangesDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void sendList(String uploadedImageUri, long timestamp) {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("List");
        HashMap<String, Object> hashMap = new HashMap<>();

        hashMap.put("firstName", firstNameString);
        hashMap.put("lastName", lastNameString);
        hashMap.put("age", ageString);
        hashMap.put("description", descriptionString);
        hashMap.put("url", uploadedImageUri);
        hashMap.put("timestamp", timestamp);

        reference.push().setValue(hashMap);
    }
}

It's because of the improper rules set to firebase storage.这是因为为 firebase 存储设置的规则不正确。 You can set the following rule for testing:您可以设置以下规则进行测试:

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

Setting the above rule would open if for public.如果为 public,则设置上述规则将打开。 Hence you have to set appropriate authentication rule for production.因此,您必须为生产设置适当的身份验证规则。

Reference from another answer https://stackoverflow.com/a/49991921/839042来自另一个答案的参考https://stackoverflow.com/a/49991921/839042

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Firebase图片上传到存储Android错误 - Firebase image uploading to storage Android error 在将图像上传到 Firebase 存储之前对其进行压缩 - Compressing an Image before Uploading it to Firebase Storage 我正在将图像上传到 Firebase 存储,然后我需要将图像 URL 作为文本添加到 Firebase 数据库中 - I am uploading image to Firebase Storage and then I need to add the image URL as text in Firebase Database 将本地数据库上传到 Firebase 存储 - Uploading a local database to Firebase Storage 图像加载和上传到 Firebase 存储在 android 和 firebase 控制台中不起作用,显示“错误加载预览” - Image loading and uploading to Firebase Storage not working in android and firebase console showing "error loading preview" 尝试通过使用默认相机应用程序使用Firebase并捕获图像并上传到Firebase存储 - Trying to work with Firebase by using Default camera app and capturing the Image and uploading to the Firebase Storage 将本地.csv上传到Firebase存储 - Uploading local .csv to Firebase Storage 将图像上传到Firebase存储后,无法将图像URL放入Firestore数据库 - Unable to put image url to Firestore database after uploading the image to firebase storage 将一个用户的图像上传到 firebase 存储时,数据库中每个用户的图像链接都会更新 - When uploading a image for one user to firebase storage, the link of the image updates for every user in database 在 Firebase 存储上上传图像 - Upload Image on Firebase Storage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM