【问题标题】:Image is not Uploading in Firebase图片未在 Firebase 中上传
【发布时间】:2019-09-28 23:59:57
【问题描述】:

我正在尝试制作一个聊天应用程序,希望用户在其中上传图像,并且我正在使用 Firebase 实时数据库来存储用户的数据。 taskSnapshot.downloadUrl() 方法已弃用,因为我使用了不同的方法将图像上传到 Firebase,如文档中所示

https://firebase.google.com/docs/storage/android/upload-files

还有这个 StackOverflow

发帖:taskSnapshot.getDownloadUrl() is deprecated 但是,图像仍然没有上传到数据库。

我还尝试过清理项目、重建项目、无效和重新启动等操作。

这是我用来将图像上传到 Firebase 实时数据库的代码:

    // ImagePickerButton shows an image picker to upload an image for a 
     message
    mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/jpeg");
            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
        }
    });

然后在 onActivityResults 方法中:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable 
Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        if (resultCode == RESULT_OK) {
            Toast.makeText(MainActivity.this, "Signed-In", 
        Toast.LENGTH_SHORT).show();
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(MainActivity.this, "Signed-In Cancel", 
        Toast.LENGTH_SHORT).show();
            finish();
        } else if (requestCode == RC_PHOTO_PICKER && resultCode == 
          RESULT_OK) {

            Uri selectedUri = data.getData();
            final StorageReference storageReference = mChatPhotosStorageReference.
                    child(selectedUri.getLastPathSegment());
            UploadTask uploadTask = storageReference.putFile(selectedUri);
            Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                @Override
                public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }

                    return storageReference.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri downloadUrl = task.getResult();
                        FriendlyMessage message = new FriendlyMessage(null, mUsername, downloadUrl.toString());
                         mMessageDatabaseReference.push().setValue(message);
                    }
                }
            });

这是完整项目的 Github 链接:https://github.com/harshabhadra/FriendlyChat

【问题讨论】:

  • 您没有进行任何错误处理。任务可能会失败,但您只编写在任务成功完成时运行的代码。如果有错误,你永远不会知道它发生了。
  • 您是否尝试过处理这些错误?你有消息吗?请回复@。
  • @AlexMamo 是的,我已经尝试处理错误,但没有收到任何消息

标签: android firebase firebase-storage


【解决方案1】:

使用它以字节为单位将照片上传到 Firebase 存储

private void uploadImage(byte[] data) {
        submitButton.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);

        final String userId = DatabaseContants.getCurrentUser().getUid();
        photo_description_edit_text.setVisibility(View.GONE);
        StorageMetadata metadata = new StorageMetadata.Builder()
                .setContentType("image/webp")
                .build();

        final String photoName = System.currentTimeMillis() + "_byUser_" + userId;
        StorageReference imageRef = StorageConstants.getImageRef(photoName + ".webp");
        UploadTask uploadTask = imageRef.putBytes(data, metadata);

        final Resources res = getResources();

        uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                double progress = 100.0 * (taskSnapshot.getBytesTransferred() /
                        taskSnapshot.getTotalByteCount());
                progressBar.setProgress((int) progress);
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size,
                // content-type, and download URL.
                Log.d(LOG_TAG, "Image is successfully uploaded: " + taskSnapshot.getMetadata());

                Uri downloadUrl = taskSnapshot.getDownloadUrl();

                Analytics.registerUpload(activity, userId);

                PhotoModel photoModel = new PhotoModel(userId, photoDescription, "none",
                        0, 0, rotation, photoName + ".webp");

                DatabaseContants.getPhotoRef().child(photoName).setValue(photoModel);

                Utils.photosUploadedCounter++;
                if (Utils.photosUploadedCounter % 2 == 0) {
                    if (mInterstitialAd.isLoaded()) {
                        mInterstitialAd.show();
                    } else {
                        Log.d("TAG", "The interstitial wasn't loaded yet.");
                    }
                }

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                NotificatonConstants.sendNotification(activity,
                        res.getString(R.string.failure_title),
                        res.getString(R.string.failure_message),
                        NotificatonConstants.UPLOAD_ID);
            }
        }).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                NotificatonConstants.sendNotification(activity,
                        res.getString(R.string.success_title),
                        res.getString(R.string.success_message),
                        NotificatonConstants.UPLOAD_ID);
            }
        });
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2021-12-23
    • 1970-01-01
    • 2021-06-28
    • 2018-02-10
    • 2020-10-05
    • 1970-01-01
    相关资源
    最近更新 更多