How to Upload a Java Project on Black Board
- Details
- Written by
- Terminal Updated on 03 Jan 2022 | Print Electronic mail
In this tutorial, you will acquire how to integrate S3 file upload functionality into a Java web application based on Leap Kick using AWS SDK for Coffee - for the purpose of hosting static resources on a deject storage service such as S3.
The following picture explains the workflow of uploading files from user's computer to Amazon S3:
Firstly, the end users cull files from their computer and submit a web form. The files will be transferred to a Spring Kick application which is running with embedded Tomcat server. And then the application uses S3 API for transferring the files to a bucket on S3 server. That means the files are transferred two times, merely the process is transparent to the users.
To follow this tutorial, yous have to setup AWS SDK on your computer.
Technologies used: Spring framework with Spring Boot; Jump MVC; Thymeleaf and AWS SDK for Java.
Software programs: Coffee Development Kit (JDK), Leap Tool Suite (STS) IDE.
1. Create Java Spring Kicking Maven Project
Create a Spring Starter projection in STS with projection type is Maven and language is Coffee. Then update the pom.xmlfile every bit follows:
<project... > <dependencyManagement> <dependencies> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>bom</artifactId> <version>ii.15.0</version> <type>pom</blazon> <telescopic>import</telescopic> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>leap-kicking-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>jump-kick-devtools</artifactId> <telescopic>runtime</telescopic> <optional>true</optional> </dependency> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>s3</artifactId> </dependency> </dependencies> </project>
As y'all can see, also the Spring Boot starter dependencies required for a typical Spring MVC web application, you need to declare dependencies for AWS SDK and S3.
2. Code Upload Form
Next, let'due south code a page that allows the users to pick a file for upload. Create an HTML file named upload.html nether src/main/resources/templates directory with the following code:
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Leap Boot File Upload to S3</championship> </head> <body> <div align="center"> <div><h2>Leap Kick File Upload to S3</h2></div> <div> <grade activeness="upload" method="mail" enctype="multipart/class-data"> <p> Description: <input type="text" proper noun="description" size="xxx" required /> </p> <p> <input type="file" name="file" required /> </p> <p> <button type="submit">Submit</push> </p> </grade> </div> </div> </trunk> </html>
At runtime, this page would look like this:
Also create the MainController class with the post-obit code:
package internet.codejava.aws; import org.springframework.stereotype.Controller; import org.springframework.spider web.bind.annotation.GetMapping; @Controller public class MainController { @GetMapping("") public Cord viewHomePage() { return "upload"; } }
This is a Spring MVC controller form that implements a handler method that handles requests coming to the homepage of the application. You can see information technology returns the logical view name "upload" which volition be resolved to the upload.html file mentioned higher up.
three. Code S3 Utility Grade for File Upload
Next, let's code a utility class that uses AWS Java SDK for implementing a method that uploads a file to Amazon S3. So create the S3Util course with the following code:
package net.codejava.aws; import java.io.IOException; import java.io.InputStream; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.cadre.exception.SdkClientException; import software.amazon.awssdk.cadre.sync.RequestBody; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.S3Exception; public class S3Util { private static terminal String BUCKET = "your-bucket-proper noun"; public static void uploadFile(String fileName, InputStream inputStream) throws S3Exception, AwsServiceException, SdkClientException, IOException { S3Client client = S3Client.builder().build(); PutObjectRequest asking = PutObjectRequest.builder() .bucket(Bucket) .central(fileName) .build(); client.putObject(asking, RequestBody.fromInputStream(inputStream, inputStream.available())); } }
This class will be used past the MainController grade, and you tin can meet the lawmaking is simple and straightforward. It uses S3 API to put an object into a S3 bucket, with object'south data is read from an InputStream object. Note that you must specify a bucket proper noun that is available in your AWS account.
Upload File to S3 with public-read permission:
By default, the file uploaded to a bucket has read-write permission for object possessor. It is non accessible for public users (everyone). If you desire to give public-read admission for public users, use the acl() method every bit below:
PutObjectRequest asking = PutObjectRequest.builder() .saucepan(BUCKET) .primal(fileName) .acl("public-read") .build();
Wait until the file exists:
In the lawmaking example in a higher place, the uploadFile() method returns immediately as the put object performance is executed asynchronously. In case you desire to run some custom logics that depend on the existence of the uploaded file, add the following lawmaking that waits until the file exists on S3:
S3Waiter waiter = client.waiter(); HeadObjectRequest waitRequest = HeadObjectRequest.builder() .bucket(Saucepan) .central(fileName) .build(); WaiterResponse<HeadObjectResponse> waitResponse = waiter.waitUntilObjectExists(waitRequest); waitResponse.matched().response().ifPresent(x -> { // run custom code that should be executed afterwards the upload file exists });
This may cause the uploadFile() method runs slower as it has to await until the file exists on S3 server, and also run your custom logics.
Set additional information for the upload file:
Y'all can use the contentXXX() methods of the PutObjectRequest class to specify additional information for the file stored on S3. For example, the following lawmaking ready content blazon of the file to be "image/png" for the file:
PutObjectRequest request = PutObjectRequest.builder() .bucket(bucketName) .key(central) .acl("public-read") .contentType("image/png") .build();
The other methods are contentDisposition(), contentEncoding(), contentLanguage(), contentLength()…
4. Lawmaking Handler Method and Bulletin Page
Next, update the MainController grade. Implement the 2nd hander method that handles the submission of the upload grade. Below is its complete code:
parcel net.codejava.aws; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.note.GetMapping; import org.springframework.spider web.bind.annotation.PostMapping; import org.springframework.web.bind.notation.RequestParam; import org.springframework.spider web.multipart.MultipartFile; @Controller public class MainController { @GetMapping("") public String viewHomePage() { return "upload"; } @PostMapping("/upload") public String handleUploadForm(Model model, Cord description, @RequestParam("file") MultipartFile multipart) { String fileName = multipart.getOriginalFilename(); Organisation.out.println("Description: " + description); Arrangement.out.println("filename: " + fileName); String message = ""; try { S3Util.uploadFile(fileName, multipart.getInputStream()); message = "Your file has been uploaded successfully!"; } take hold of (Exception ex) { message = "Error uploading file: " + ex.getMessage(); } model.addAttribute("bulletin", message); return "message"; } }
As you tin see, it uses the S3Util form for transferring the uploaded file to Amazon S3, and returns the view proper name "message" which will be resolved to the message.html file whose code is as below:
<!DOCTYPE html> <html> <caput> <meta charset="ISO-8859-1"> <championship>Leap Kicking File Upload to S3</title> </head> <torso> <div marshal="center"> <div><h3>[[${message}]]</h3></div> </div> </torso> </html>
In this file, we simply use a Thymleaf expression to print value of an attribute named "message", which is prepare in the controller class.
5. Examination Uploading Files to Amazon S3
Run the Spring Kicking project and admission the URL http://localhost:8080/ in a spider web browser. You would see the upload page like this:
Enter some text into the description field, then cull a file and click Submit button. Wait a moment, and you will see the message folio like this:
Now, sign in to your AWS account and check the bucket you used in the lawmaking. Y'all should see the file appears in that location.
That's my tutorial virtually adding S3 file upload function to a Spring Boot application. To run across the coding in activity, sentry the following video:
Y'all can also download the sample project attached below.
Related AWS Java SDK Tutorials:
- How to Generate AWS Access Cardinal ID and Secret Access Key
- How to setup AWS SDK for Java for Amazon S3 Development
- AWS Java SDK S3 Listing Buckets Instance
- AWS Java SDK S3 List Objects Examples
- AWS Java SDK S3 Create Bucket Examples
- AWS Java SDK S3 Create Folder Examples
- Upload File to S3 using AWS Jav SDK - Java Console Program
- Upload File to S3 using AWS Coffee SDK - Java Servlet JSP Spider web App
- AWS Java SDK Download File from S3 Example
- AWS Coffee SDK S3 Delete Objects Examples
- AWS Coffee SDK S3 Delete Buckets Examples
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java ane.4 and has been falling in honey with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Source: https://www.codejava.net/aws/upload-file-to-s3-spring-boot
0 Response to "How to Upload a Java Project on Black Board"
Postar um comentário