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

时间:2018-12-12 16:19:16

标签: grails groovy google-cloud-platform google-cloud-storage

我正在制作一个需要将Excel文件上传到Google存储空间的应用。

有人可以告诉我如何使用GoogleServiceAuthentication在Google存储空间中上传文件吗?

我正在尝试通过操作excelFileFileUploadController上传到uploadExcelFile

代码:

def uploadExcelFile(){

    def excelFile = request.getFile('excelFile')

    // UPLOAD HERE 

    redirect(action: "index")
}

1 个答案:

答案 0 :(得分: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}