Java Upload File to S3 Cloud Server
- Details
- Written by
- Terminal Updated on 03 January 2022 | Print Email
In this AWS S3 Java SDK tutorial, I'd similar to guide you through the evolution of a Java spider web application based on Servlet & JSP, which allows users to upload files from their local computer, and and then the files will be transferred to a saucepan on Amazon S3 server. It would be transparent to the finish users, for the purpose of hosting static resources in a cloud storage service like S3.
The post-obit moving-picture show explains the workflow of files uploaded to Amazon S3:
As yous tin see, a file will exist uploaded ii times. Firstly, information technology is transferred from the user'due south computer to the application server (e.1000. Apache Tomcat) which hosts the Coffee spider web app, which transfers the file to a saucepan on S3 server programmatically using AWS SDK for Java. That ways the files are stored on the application server temporarily.
Before following this tutorial, I recommend you to check the article How to setup AWS SDK for Coffee for S3.
Software programs required: Java Development Kit (JDK), Apache Tomcat 9.0 server, Eclipse IDE.
1. Setup Java Spider web Maven project
In Eclipse IDE, create a Coffee Dynamic Web project, and and then catechumen to Maven project (follow this guide). Then update the pom.xml file with the following dependency information:
<project ...> <dependencyManagement> <dependencies> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>bom</artifactId> <version>2.15.0</version> <type>pom</type> <telescopic>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>s3</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>iv.0.ane</version> <scope>provided</scope> </dependency> </dependencies> </project>
Every bit you lot tin can see, at least two dependencies required: S3 and Java Servlet.
ii. Code File Upload Form
Next, let's code a JSP page that allows the finish users to option a file from their local calculator. Create the upload.jsp file nether WebContent (or webapp) folder, with the post-obit lawmaking:
<div><h1>S3 Upload File Example</h1></div> <div> <course action="upload" method="post" enctype="multipart/form-data"> <p>Clarification: <input type="text" name="description" size="30" required /></p> <p><input blazon="file" name="file" required /></p> <p><button blazon="submit">Submit</button></p> </grade> </div>
The file upload page would look similar this in web browser:
Here, on this form, we can type some clarification text and choose a file to be uploaded.
3. Code S3 Utility class
Next, lawmaking a utility class that implements code for uploading a file to a bucket on Amazon S3 server, using S3 API provided by the AWS SDK. Here's the code:
package net.codejava.aws; import java.io.IOException; import java.io.InputStream; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.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 last String BUCKET = "your-bucket-proper name"; public static void uploadFile(String fileName, InputStream inputStream) throws S3Exception, AwsServiceException, SdkClientException, IOException { S3Client client = S3Client.architect().build(); PutObjectRequest request = PutObjectRequest.builder() .bucket(BUCKET) .cardinal(fileName) .acl("public-read") .build(); client.putObject(request, RequestBody.fromInputStream(inputStream, inputStream.bachelor())); } }
The code is pretty elementary and straightforward. You should specify a bucket name in your AWS S3 account. The higher up code transfers a file that is read from an InputStream to the specified S3 bucked.
Note that the file will be stored in S3 with public-read permission, meaning that it is attainable to anybody - which is suitable for hosting public static resource (images, JS, CSS, …). If you desire to keep the files private, do not use the acl() method.
Wait until the file exists on S3:
And the put object functioning is executed asynchronously, meaning the uploadFile() method returns immediately, regardless of the file completely transferred or not. And then if y'all want to run some logics that depend on the being of the file on S3, consider calculation the following code:
S3Waiter waiter = client.waiter(); HeadObjectRequest waitRequest = HeadObjectRequest.architect() .bucket(Bucket) .key(fileName) .build(); WaiterResponse<HeadObjectResponse> waitResponse = waiter.waitUntilObjectExists(waitRequest); waitResponse.matched().response().ifPresent(response -> { // run custom logics when the file exists on S3 });
By using this lawmaking snippet, the uploadFile() method will render when the file exists on S3 (uploaded completely).
Set additional information for the upload file:
You can use the contentXXX() methods of the PutObjectRequest class to specify additional information for the file stored on S3. For instance, the following code set content type of the file to be "image/png" for the file:
PutObjectRequest request = PutObjectRequest.builder() .saucepan(bucketName) .key(cardinal) .acl("public-read") .contentType("image/png") .build();
The other methods are contentDisposition(), contentEncoding(), contentLanguage(), contentLength()…
4. Code File Upload Servlet Class
Next, code a Java servlet form that handles submission of the upload form. Beneath is the code:
bundle internet.codejava.aws; import coffee.io.IOException; import javax.servlet.ServletException; import javax.servlet.notation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Function; @WebServlet("/upload") @MultipartConfig( fileSizeThreshold = 1024*1024*2, // 2MB maxFileSize = 1024*1024*10, // 10MB maxRequestSize = 1024*1024*eleven // 11MB ) public form FileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public FileUploadServlet() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cord clarification = request.getParameter("description"); Arrangement.out.println("Description: " + clarification); Part filePart = asking.getPart("file"); String fileName = getFileName(filePart); System.out.println("File proper noun = " + fileName); Cord message = ""; effort { S3Util.uploadFile(fileName, filePart.getInputStream()); message = "The file has been uploaded successfully"; } grab (Exception ex) { bulletin = "Error uploading file: " + ex.getMessage(); } request.setAttribute("message", message); request.getRequestDispatcher("message.jsp").frontwards(request, response); } private Cord getFileName(Part role) { Cord contentDisposition = part.getHeader("content-disposition"); int beginIndex = contentDisposition.indexOf("filename=") + 10; int endIndex = contentDisposition.length() - one; return contentDisposition.substring(beginIndex, endIndex); } }
Note that nosotros demand to use the @MultipartConfigannotation for this servlet class like this:
@MultipartConfig( fileSizeThreshold = 1024*1024*2, // 2MB maxFileSize = 1024*1024*10, // 10MB maxRequestSize = 1024*1024*eleven // 11MB )
You lot can change the values accordingly, based you lot your application's need. The fileSizeThreshold value specifies the threshold beyond which the file will be stored on disk temporarily (otherwise the file is stored in memory); maxFileSize is the maximum of the file which users can upload per request; maxRequestSize is the total size of a HTTP request, including form data.
5. Code Message JSP Page
As you can see in the doPost() method of the FileUploadServlet class above, information technology always redirects users to a JSP page named message.jsp - to show successful message or error message. And so create the message.jsp file under WebContent (webapp) with the following HTML lawmaking in the torso:
<body> <div align="center"> <div><h3>${bulletin}</h3></div> </div> </body>
It simply prints the value of an attribute named message, which ready in the servlet class to a higher place.
six. Test Uploading Files to Amazon S3
Now, you tin can run the project in Eclipse past deploying it on Apache Tomcat server. Follow this video if you don't know how. Then access the awarding's home page at this URL:
http://localhost:8080/S3FileUploadExample/
The upload form should appear every bit shown below:
Enter some text into description field, and cull a file. And so click Submit. Wait a moment. If everything is going smoothly, y'all should encounter the message page:
At present, sign in your AWS business relationship. Go to S3 service, go in the saucepan you specified in the code. Be sure that the file exists there.
That'southward my tutorial about coding S3 file upload functionality in a Java web application based on Servlet and JSP. To see the coding in action, I recommend you watch the following video:
Yous tin can too download the sample project fastened below.
Related AWS Coffee SDK Tutorials:
- How to Generate AWS Admission Key ID and Secret Access Central
- How to setup AWS SDK for Coffee for Amazon S3 Development
- AWS Coffee SDK S3 List Buckets Case
- AWS Java SDK S3 Listing Objects Examples
- AWS Java SDK S3 Create Bucket Examples
- AWS Java SDK S3 Create Folder Examples
- Upload File to S3 using AWS Jav SDK - Coffee Console Plan
- Spring Boot File Upload to Amazon S3 Case
- AWS Java SDK Download File from S3 Example
- AWS Coffee SDK S3 Delete Objects Examples
- AWS Coffee SDK S3 Delete Buckets Examples
About the Writer:
Nam Ha Minh is certified Java developer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in dear with Coffee 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-java-servlet-jsp
0 Response to "Java Upload File to S3 Cloud Server"
Post a Comment