简体   繁体   English

Firebase Cloud Storage Java Admin SDK 上传带有 contentType 的文件

[英]Firebase Cloud Storage Java Admin SDK upload file with contentType

I'm able to upload files on Google Cloud Storage using Firebase Admin SDK.我可以使用 Firebase Admin SDK 在 Google Cloud Storage 上上传文件。 However, I'm unable to set the correct contentType for the file and the uploaded file defaults to application/octet-stream .但是,我无法为文件设置正确的 contentType 并且上传的文件默认为application/octet-stream I'm unable to any documentations for setting the correct contentType/metadata using Java Admin SDK.我无法使用 Java Admin SDK 设置正确的 contentType/元数据的任何文档。 How I can change the default contentType?如何更改默认的 contentType?

Here's the code snippet on how I upload the file.这是关于我如何上传文件的代码片段。

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);

Turns out that I need to use Google Cloud Storage API .原来我需要使用Google Cloud Storage API The docs for Firebase Cloud Storage for Admin SDK is barren. Firebase Cloud Storage for Admin SDK 的文档很贫乏。 I hope that the docs were clearer.我希望文档更清楚。

Here's the snippet on how I modified the contentType for my file upload.这是我如何修改文件上传的 contentType 的片段。 This changed the contentType from application/octet-stream to text/csv这将 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);
}

I'm still unable to download the uploaded file on Firebase Storage dashboard , but the uploaded file can be downloaded through Google Cloud Storage dashboard .我仍然无法在Firebase Storage 仪表板上下载上传的文件,但可以通过Google Cloud Storage 仪表板下载上传的文件。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM