java - Firebase 存储 - 防止覆盖文件

标签 java android firebase android-camera firebase-storage

我允许用户拍照并将其存储到 Firebase。下面是我的代码,其中包含加载相机应用程序、保存图像,然后上传到 Firebase 存储的 Intent 。我遇到的问题是每次后续上传到 Firebase 存储都会覆盖之前的上传,这意味着我的存储中有 1 个文件不断被覆盖。我想继续添加多个文件:

private void createAlertDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.add_image_dialog_title);
    builder.setItems(new CharSequence[]
                    {getResources().getString(R.string.add_image_web), getResources().getString(R.string.add_image_camera), getResources().getString(R.string.add_image_gallery)},
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // The 'which' argument contains the index position
                    // of the selected item
                    switch (which) {
                        case 0:
                            Intent toImageSearch = new Intent(CreateActivity.this, NewImageActivity.class);
                            startActivityForResult(toImageSearch, USE_WEB);
                            break;
                        case 1:
                            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (takePictureIntent.resolveActivity(getApplication().getPackageManager()) != null) {
                                startActivityForResult(takePictureIntent, TAKE_PICTURE);
                            } else {
                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.camera_error), Toast.LENGTH_LONG).show();
                            }
                            break;
                        case 2:
                            Toast.makeText(getApplicationContext(), "clicked 2", Toast.LENGTH_LONG).show();
                            break;
                        case 3:
                            Toast.makeText(getApplicationContext(), "clicked 3", Toast.LENGTH_LONG).show();
                            break;
                    }
                }
            }

    );
    builder.create().

            show();
}

OnActivityResult()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case USE_WEB:
            if (resultCode == CreateActivity.RESULT_OK) {
                resultImageURL = data.getStringExtra("result");
                mAddImageButton.setVisibility(View.INVISIBLE);
                Picasso.with(getApplicationContext())
                        .load(resultImageURL)
                        .into(mImagePreview);
            }
            if (resultCode == CreateActivity.RESULT_CANCELED) {
                //Write your code if there's no result
            }

        case TAKE_PICTURE:
            if (resultCode == CreateActivity.RESULT_OK) {
                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                mImagePreview.setImageBitmap(imageBitmap);
                encodeBitmapAndSaveToFirebase(imageBitmap);
            }
    }
}

保存到 Firebase:

 private void encodeBitmapAndSaveToFirebase(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] data = baos.toByteArray();

    UploadTask uploadTask = mPollImageStorage.putBytes(data);
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Toast.makeText(getApplicationContext(), "Error Loading Photo", Toast.LENGTH_LONG).show();
        }
    }).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.
            Uri downloadUrl = taskSnapshot.getDownloadUrl();
            mAddImageButton.setVisibility(View.INVISIBLE);
            resultImageURL = downloadUrl.toString();
            Picasso.with(getApplicationContext())
                    .load(resultImageURL)
                    .into(mImagePreview);
        }
    });

}

最佳答案

您需要为每次上传使用单独的位置或单独的文件名。

您可以创建一个自定义位置,如下所示:

 FirebaseStorage storage = FirebaseStorage.getInstance();
            StorageReference storageRef = storage.getReferenceFromUrl("gs://myfirebaseproject.appspot.com");
            StorageReference fileRef =
                    storageRef.child(channelId)
                    .child(String.valueOf(message.getSender()))
                    .child(String.valueOf(message.getTimestamp()));

            UploadTask uploadTask = fileRef.putFile(message.getAttachmentUri());
            uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    sendMessage(channelId, message.getMessageText(), taskSnapshot.getStorage().toString(), message.getAttachmentType(), callback);
                }
            });
            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    callback.onError(e.toString());
                }
            }); 

您可以看到我们正在将自定义位置添加到我们的基本存储引用中,以便我们不会覆盖现有项目。

关于java - Firebase 存储 - 防止覆盖文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41309280/

相关文章:

java - HQL 不接受带有 join 的更新 SQL

PreAuthorize 注释中的 Java 8/Spring 常量

java - Excel 单元格 POI 的多种样式

android - 使用 sencha touch 2 开发的应用程序的推送通知

ios - 处理构建短语中的不同配置后找不到有效的 GoogleService-Info.plist

Java网络启动: download only the first time?

Android Intent 发布 URL?

android - 默认 Android 4 应用程序的源代码(时钟闹钟定时器)

ios - 在谷歌登录后使用 Swift 4 推送 View Controller

node.js - Firebase 功能 - 错误,但控制台中没有事件消息