【问题标题】:Firebase Cloud Storage Java Admin SDK upload file with contentTypeFirebase Cloud Storage Java Admin SDK 使用 contentType 上传文件
【发布时间】:2021-12-07 01:29:31
【问题描述】:

我可以使用 Firebase Admin SDK 在 Google Cloud Storage 上上传文件。但是,我无法为文件设置正确的 contentType,并且上传的文件默认为 application/octet-stream。我无法使用 Java Admin SDK 设置正确的内容类型/元数据的任何文档。如何更改默认 contentType?

这是我如何上传文件的代码 sn-p。

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

【问题讨论】:

    标签: java google-cloud-storage firebase-storage


    【解决方案1】:

    原来我需要使用Google Cloud Storage API。用于 Admin SDK 的 Firebase Cloud Storage 的 docs 是无效的。我希望文档更清晰。

    这是关于我如何修改文件上传的 contentType 的 sn-p。这将 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下载上传的文件,但是上传的文件可以通过Google Cloud Storage dashboard下载。

    【讨论】:

      猜你喜欢
      • 2021-03-19
      • 1970-01-01
      • 2020-11-21
      • 2020-10-15
      • 2019-01-16
      • 2019-04-08
      • 2019-08-02
      • 2020-05-09
      • 1970-01-01
      相关资源
      最近更新 更多