Jakov
Jakov

Reputation: 989

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

I am making an app in which I need to upload Excel files to Google Storage.

Can someone tell me how to upload file in Google Storage by using GoogleServiceAuthentication?

I am trying to upload excelFile in FileUploadController by using action uploadExcelFile.

CODE:

def uploadExcelFile(){

    def excelFile = request.getFile('excelFile')

    // UPLOAD HERE 

    redirect(action: "index")
}

Upvotes: 0

Views: 195

Answers (1)

MikeM
MikeM

Reputation: 71

You will need to setup a service account under IAM and grant the account access to your storage bucket. Once the account is created, you can download the private key in json format. You can then use that key in your code:

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

Storage storage = options.getService();

Once you have your storage object, you can retrieve your bucket and upload files to it:

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

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

Upvotes: 1

Related Questions