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

问题描述 投票:0回答:1

我正在创建一个应用程序,我需要将Excel文件上传到Google Storage。

有人可以告诉我如何使用Google服务身份验证在Google Storage中上传文件吗?

我试图通过使用动作excelFile上传FileUploadController中的uploadExcelFile

码:

def uploadExcelFile(){

    def excelFile = request.getFile('excelFile')

    // UPLOAD HERE 

    redirect(action: "index")
}
grails groovy google-cloud-platform google-cloud-storage
1个回答
1
投票

您需要在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}
© www.soinside.com 2019 - 2024. All rights reserved.