图片未在Firebase中上载

时间:2019-05-11 08:01:09

标签: android firebase firebase-storage

我正在尝试创建一个聊天应用程序,希望用户在该应用程序中上传图像,并且我正在使用Firebase RealTime数据库存储用户的数据。 taskSnapshot.downloadUrl()方法已过时,因为我使用了另一种方法将图像上传到Firebase,如文档

所示

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

和此StackOverflow

帖子:taskSnapshot.getDownloadUrl() is deprecated 但是,图像仍未上传到数据库。

我还尝试了诸如清理项目,重建项目,无效和重新启动之类的事情。

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

    // 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

1 个答案:

答案 0 :(得分:0)

使用此文件以字节为单位将照片上传到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);
            }
        });
    }