Firebase 云存储 Java Admin SDK 上传包含 contentType 的文件

Firebase Cloud Storage Java Admin SDK upload file with contentType

我可以使用 Firebase Admin SDK 在 Google 云存储上上传文件。但是,我无法为文件设置正确的 contentType,上传的文件默认为 application/octet-stream。我无法使用 Java Admin SDK 设置正确的 contentType/metadata 的任何文档。如何更改默认的 contentType?

这是我上传文件的代码片段。

Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String timestamp = dateFormat.format(date);
StorageClient storageClient = StorageClient.getInstance();
Bucket storageBucket = storageClient.bucket();

// Not sure if I'm doing this correctly
BlobInfo blobInfo = BlobInfo.newBuilder(storageBucket.getName(), "filename")
        .setContentType("vnd.ms-excel").build();

// File upload task
storageClient.bucket().create(backupFolderPath + fileNamePrefix + "_" + timestamp + ".csv", file);

原来我需要使用 Google Cloud Storage API. The docs 因为 Admin SDK 的 Firebase 云存储是贫瘠的。我希望文档更清楚。

这是我如何修改文件上传的 contentType 的片段。这将 contentType 从 application/octet-stream 更改为 text/csv

Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String timestamp = dateFormat.format(date);
StorageClient storageClient = StorageClient.getInstance();

try {
  String bucketName = "<YOUR_BUCKET_NAME>";
  String objectName = backupFolderPath + fileNamePrefix + "_" + timestamp + ".csv";
  BlobId blobId = BlobId.of(bucketName, objectName);
  
  // Configure BlobInfo
  BlobInfo blob = BlobInfo.newBuilder(blobId)
      .setContentType("text/csv")
      .setContentEncoding("utf-8").build();

  // Use fetch `storage` from the bucket
  // https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-code-sample
  storageClient.bucket().getStorage().create(blob, 
      Files.readAllBytes(Paths.get("backup/accounts.csv")));
} catch (IOException e) {
  logger.error(">>>>> Message from Scheduled Job " + e);
}

我仍然无法在 Firebase Storage dashboard, but the uploaded file can be downloaded through Google Cloud Storage dashboard 下载上传的文件。