简体   繁体   中英

Upload file to google cloud storage (JAVA)

I want to upload a file to Google Cloud Storage following the example provided at official documentation

  public class UploadObject {
      public static void uploadObject(
          String projectId, String bucketName, String objectName, String filePath) throws IOException {
        // The ID of your GCP project
        // String projectId = "your-project-id";
    
        // The ID of your GCS bucket
        // String bucketName = "your-unique-bucket-name";
    
        // The ID of your GCS object
        // String objectName = "your-object-name";
    
        // The path to your file to upload
        // String filePath = "path/to/your/file"
    
        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);
      }
    }

Nevertheless, I'm getting the error:

Exception in thread "main" com.google.cloud.storage.StorageException: Error getting access token for service account: 400 Bad Request {"error":"invalid_grant","error_description":"Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values in the JWT claim."} at com.google.cloud.storage.spi.v1.HttpStorageRpc.translate(HttpStorageRpc.java:227)

What could be the cause of this?

This error has two common causes: the clock where you are executing your task is not in sync with NTP (Network Time Protocol), or, you could check how you are handling the refresh tokens and the old tokens. When the number of refresh tokens exceeds the limit, older tokens become invalid. If the application attempts to use an invalidated refresh token, this error is returned. Take a look at this document

On the other hand, there are other options that could help you to upload a file to Cloud Storage, you can find a very clear example about how to do it using Cloud SDK through the command:

gsutil cp [OBJECT_LOCATION] gs://[DESTINATION_BUCKET_NAME]/

Here you can find more examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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