将文件上传到Google云存储(JAVA)

时间:2020-07-08 16:01:18

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

我想按照官方documentation上提供的示例将文件上传到Google云端存储

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

但是,我得到了错误:

线程“ main”中的异常com.google.cloud.storage.StorageException:获取服务帐户的访问令牌时出错:400错误的请求{“错误”:“ invalid_grant”,“ error_description”:“无效的JWT:令牌必须是短暂的令牌(60分钟),并且要在合理的时间范围内。请在JWT声明中检查iat和exp值。“} com.google.cloud.storage.spi.v1.HttpStorageRpc.translate(HttpStorageRpc。 java:227)

这可能是什么原因?

1 个答案:

答案 0 :(得分:0)

此错误有两个常见原因:执行任务的时钟与NTP(网络时间协议)不同步,或者您可以检查如何处理刷新令牌和旧令牌。当刷新令牌的数量超过限制时,较早的令牌将变为无效。如果应用程序尝试使用无效的刷新令牌,则会返回此错误。看看这个document

另一方面,还有其他选项可以帮助您将文件上传到Cloud Storage,您可以通过以下命令找到非常清晰的example关于如何使用Cloud SDK的信息:

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

Here,您可以找到更多示例。