如何使用 GoogleServiceAuthentication class 将文件上传到 grails 中的 google 存储?

How to upload file to google storage in grails by using GoogleServiceAuthentication class?

我正在制作一个应用程序,我需要在其中上传 Excel 个文件到 Google 存储空间。

谁能告诉我如何使用 GoogleServiceAuthentication 在 Google 存储中上传文件?

我正在尝试使用操作 uploadExcelFile.

FileUploadController 中上传 excelFile

代码:

def uploadExcelFile(){

    def excelFile = request.getFile('excelFile')

    // UPLOAD HERE 

    redirect(action: "index")
}

您需要在 IAM 下设置一个服务帐户并授予该帐户访问您的存储桶的权限。创建帐户后,您可以下载 json 格式的私钥。然后您可以在您的代码中使用该键:

StorageOptions options = StorageOptions.newBuilder()
    .setCredentials(GoogleCredentials.fromStream(new ByteArrayInputStream("YOUR KEY FROM JSON FILE".getBytes())))
    .build();

Storage storage = options.getService();

拥有存储对象后,您可以检索存储桶并将文件上传到其中:

Bucket bucket = storage.get("your-bucket-name")

try {
    bucket.create("name of file", excelFile.inputStream)
}
catch (Exception e) {//do something}