How to Upload File to AWS S3 using Grails 3 and AWS SDK S3 Plugin

by Didin J. on Sep 16, 2017 How to Upload File to AWS S3 using Grails 3 and AWS SDK S3 Plugin

Step by step tutorial on how to upload file to Amazon AWS S3 using Grails 3 and AWS SDK S3 Plugin.

This tutorial shows you how to upload the file to Amazon AWS S3 bucket using Grails 3 and AWS SDK S3 Plugin. This plugin is sub plugin of Grails-AWS plugin which uses for several services on the Amazon AWS infrastructure. The following tools, plugin, and dependencies are required:

- JDK 8
- Grails 3 (Latest version 3.3.0)
- AWS SDK S3 Plugin
- Terminal or Command Line
- Text Editor or IDE

We assume that you already installed JDK 8 and able to run Grails 3. In this tutorial, we are not cover how to create Amazon AWS account and get Access and Secret Key. So, we assume too that you already have it. To get Access and Secret Key you can find on official documentation.


1. Create a New Grails 3 Application

As usual, we starting the tutorial from scratch that's mean start from zero. Open your terminal or command line (cmd) then go to your projects folder then type this command.

grails create-app grails3-aws-s3-upload

Go to the newly created Grails 3 application project folder.

cd grails3-aws-s3-upload

Type this command to enter the Grails 3 interactive console.

grails

Now, you are in Grails 3 interactive console.

| Resolving Dependencies. Please wait...

CONFIGURE SUCCESSFUL

| Starting interactive mode...
| Enter a command name to run. Use TAB for completion:
grails>

Don't forget to make sure everything working properly by running the application. Type this command in the Grails 3 interactive console for running the Grails 3 application.

run-app

Open your browser the go to this address `http://localhost:8080` and you will see this page if everything working properly.

How to Upload File to AWS S3 using Grails 3 and AWS SDK S3 Plugin - Grails 3 Home


2. Install and Configure Grails 3 AWS S3 Plugin

To install Grails 3 AWS S3 Plugin, just open and edit `build.gradle` on the root of project folder then add this line inside dependencies section (not inside buildscript).

compile 'org.grails.plugins:aws-sdk-s3:2.1.5'

Also, add this line to repositories sections (not inside buildscript).

maven { url 'http://dl.bintray.com/agorapulse/libs' }

Now, compile the application by type this command inside Grails 3 interactive console.

compile

Next, open and edit `grails-app/conf/application.yml` then add this lines before `endpoints: jmx:` and under `views: gsp: ` or where ever inside `grails:`.

plugin:
    awssdk:
        region: ap-southeast-1
        accessKey: AKIA...
        secretKey: TO4q...

If you want to enable to upload larger file size than 100KB, then you should add this lines inside `controllers: ` below `deafultscopes:`.

upload:
    maxFileSize: 5000000
    maxRequestSize: 5000000

That will enable file size for upload up to 5MB.


3. Implementing File Upload to Amazon AWS S3

To implementing file upload to Amazon AWS S3, create a new Controller by typing this command inside Grails 3 interactive console.

create-controller Uploader

Next, open and edit `grails-app/controllers/grails3/aws/s3/upload/Uploader.groovy` then add this import.

import org.springframework.web.multipart.MultipartFile
import com.amazonaws.services.s3.model.ObjectListing
import com.amazonaws.services.s3.model.S3ObjectSummary

Declare Amazon S3 Service below class name.

def amazonS3Service

Replace all `index` method with this.

def index() {
  ObjectListing listObjects = amazonS3Service.listObjects('djamblog', 'testupload/')
  List<S3ObjectSummary> objectSummary = listObjects.getObjectSummaries()

  [objects: objectSummary]
}

Add new function for upload file.

def uploadFile() {
  MultipartFile multipartFile = request.getFile('file')
  if(multipartFile && !multipartFile.empty) {
    amazonS3Service.storeMultipartFile('djamblog', 'testupload/'+multipartFile.originalFilename, multipartFile)

    flash.message = "File "+multipartFile.originalFilename+" uploaded successfully"
    redirect controller: "uploader"
  } else {
    flash.message = "Upload failed"
    redirect controller: "uploader"
  }
}

Add new function for delete file on AWS S3.

def deleteFile() {
  def found = amazonS3Service.exists('djamblog', params.filekey)
  if(found) {
    amazonS3Service.deleteFile('djamblog', params.filekey)
    flash.message = "File "+params.filekey+" deleted"
    redirect controller: "uploader"
  }
}

Now, for the view we have to create a new `grails-app/views/uploader/index.gsp` file. Replace or add this lines on that file with this.

<!doctype html>
<html>
<head>
    <meta name="layout" content="main"/>
    <title>Grails 3 AWS Uploader</title>

    <asset:link rel="icon" href="favicon.ico" type="image/x-ico" />
</head>
<body>
    <div id="content" role="main">
        <section class="row colset-2-its">
            <h2>Grails 3 AWS Uploader</h2>
            <g:if test="${flash.message}">
              <div class="message" role="alert">
                ${flash.message}
              </div>
            </g:if>
            <g:uploadForm action="uploadFile" >
              <fieldset>
                <div class="fieldcontain">
                  <input type="file" name="file" />
                </div>
              </fieldset>
              <fieldset>
                <g:submitButton name="uploadbutton" class="save" value="Upload" />
              </fieldset>
            </g:uploadForm>
        </section>
        <section class="row colset-2-its">
          <table>
            <tbody>
              <g:each in="${objects}" var="o" status="s">
                <tr>
                  <td><a href="https://s3-ap-southeast-1.amazonaws.com/djamblog/${o.key}" target="_blank">${o.key}</a></td>
                  <td><g:link action="deleteFile" class="delete" params="[filekey:o.key]">Delete</g:link></td>
                </tr>
              </g:each>
            </tbody>
          </table>
        </section>
    </div>

</body>
</html>

You might change the URL for accessing the file depends on your AWS S3 URL.


4. Test Upload File to AWS S3

It's a time for test the application uploading file to AWS S3. Run the application on the browser then go to `http://localhost:8080/uploader` and you should get this page.

How to Upload File to AWS S3 using Grails 3 and AWS SDK S3 Plugin - Grails 3 AWS S3 Uploader Page

Now, you can test upload file and see the file below the form if upload success.

That it's for now, you can grab the full source code on our GitHub.

Thanks!