San Jaisy
San Jaisy

Reputation: 17078

Set type of object while uploading to google cloud storage using java library

Using Java library to uploading the object to GCP https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-code-sample with the below code

public static void uploadObject(
      String projectId, String bucketName, String objectName, String filePath) throws IOException {
    
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
    storage.create(blobInfo, Files.readAllBytes(Paths.get(filePath)));

    System.out.println(
        "File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
  }

The above code works well, but the content type of the image is application/octet-stream How do I set to image/jpg or image/png. How can I set the meta-data before uploading

Upvotes: 1

Views: 1173

Answers (1)

jcompetence
jcompetence

Reputation: 8383

BlobInfo has a Builder which has a lot of options including setContentType.

https://googleapis.dev/java/google-cloud-storage/latest/com/google/cloud/storage/BlobInfo.Builder.html

If you always see builder/newBuilder, you need to investigate the documentation further to see if there are other (setters).

BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("image/jpeg").build();

=== Edited ===

public String determineContentType(File inputFile){

   String contentType =  // Your logic of determining type of file format

  return contentType;

}

    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType(determineContentType(yourFile)).build();

Upvotes: 6

Related Questions