How to Upload Xml File to Aws S3 Java Sdk
- Details
- Written past
- Last Updated on 03 January 2022 | Print Email
In this AWS S3 Java SDK tutorial, I'd similar to guide you lot through the development of a Java spider web application based on Servlet & JSP, which allows users to upload files from their local computer, and then the files volition exist transferred to a bucket on Amazon S3 server. It would be transparent to the stop users, for the purpose of hosting static resource in a cloud storage service like S3.
The post-obit picture explains the workflow of files uploaded to Amazon S3:
Every bit yous can see, a file volition be uploaded two times. Firstly, it is transferred from the user's reckoner to the awarding server (e.g. Apache Tomcat) which hosts the Java web app, which transfers the file to a saucepan on S3 server programmatically using AWS SDK for Coffee. That means the files are stored on the application server temporarily.
Earlier following this tutorial, I recommend y'all to check the commodity How to setup AWS SDK for Coffee for S3.
Software programs required: Java Evolution Kit (JDK), Apache Tomcat 9.0 server, Eclipse IDE.
i. Setup Java Web Maven projection
In Eclipse IDE, create a Coffee Dynamic Spider web projection, and so convert to Maven project (follow this guide). So update the pom.xml file with the following dependency information:
<project ...> <dependencyManagement> <dependencies> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>bom</artifactId> <version>two.15.0</version> <type>pom</type> <scope>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>4.0.i</version> <scope>provided</scope> </dependency> </dependencies> </project>
As you can see, at least ii dependencies required: S3 and Java Servlet.
2. Code File Upload Form
Next, let'southward code a JSP page that allows the finish users to pick a file from their local estimator. Create the upload.jsp file under WebContent (or webapp) folder, with the following code:
<div><h1>S3 Upload File Example</h1></div> <div> <form action="upload" method="post" enctype="multipart/form-data"> <p>Description: <input type="text" name="clarification" size="30" required /></p> <p><input type="file" name="file" required /></p> <p><button type="submit">Submit</button></p> </form> </div>
The file upload page would look like this in web browser:
Here, on this class, nosotros tin type some description text and choose a file to be uploaded.
iii. Code S3 Utility class
Side by side, code a utility grade that implements code for uploading a file to a saucepan on Amazon S3 server, using S3 API provided past the AWS SDK. Here's the code:
package net.codejava.aws; import coffee.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 grade S3Util { private static final String Saucepan = "your-bucket-name"; public static void uploadFile(Cord fileName, InputStream inputStream) throws S3Exception, AwsServiceException, SdkClientException, IOException { S3Client client = S3Client.builder().build(); PutObjectRequest asking = PutObjectRequest.builder() .bucket(BUCKET) .key(fileName) .acl("public-read") .build(); customer.putObject(request, RequestBody.fromInputStream(inputStream, inputStream.bachelor())); } } The code is pretty simple 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.
Notation that the file volition exist stored in S3 with public-read permission, meaning that it is accessible to everyone - which is suitable for hosting public static resources (images, JS, CSS, …). If y'all desire to keep the files individual, do non use the acl() method.
Expect until the file exists on S3:
And the put object operation is executed asynchronously, significant the uploadFile() method returns immediately, regardless of the file completely transferred or not. So if you desire to run some logics that depend on the existence of the file on S3, consider adding the following code:
S3Waiter waiter = client.waiter(); HeadObjectRequest waitRequest = HeadObjectRequest.builder() .bucket(Bucket) .fundamental(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 code snippet, the uploadFile() method volition render when the file exists on S3 (uploaded completely).
Set additional information for the upload file:
You can apply the contentXXX() methods of the PutObjectRequest form to specify additional information for the file stored on S3. For example, the following code fix content blazon of the file to be "image/png" for the file:
PutObjectRequest request = PutObjectRequest.builder() .saucepan(bucketName) .key(key) .acl("public-read") .contentType("image/png") .build(); The other methods are contentDisposition(), contentEncoding(), contentLanguage(), contentLength()…
4. Code File Upload Servlet Grade
Next, lawmaking a Java servlet class that handles submission of the upload form. Below is the lawmaking:
package net.codejava.aws; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.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.Part; @WebServlet("/upload") @MultipartConfig( fileSizeThreshold = 1024*1024*2, // 2MB maxFileSize = 1024*1024*ten, // 10MB maxRequestSize = 1024*1024*11 // 11MB ) public course FileUploadServlet extends HttpServlet { private static concluding long serialVersionUID = 1L; public FileUploadServlet() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String clarification = request.getParameter("description"); Organization.out.println("Clarification: " + description); Part filePart = asking.getPart("file"); String fileName = getFileName(filePart); System.out.println("File proper noun = " + fileName); Cord bulletin = ""; try { S3Util.uploadFile(fileName, filePart.getInputStream()); message = "The file has been uploaded successfully"; } grab (Exception ex) { bulletin = "Fault uploading file: " + ex.getMessage(); } asking.setAttribute("message", message); request.getRequestDispatcher("message.jsp").forward(request, response); } private String getFileName(Part part) { String contentDisposition = part.getHeader("content-disposition"); int beginIndex = contentDisposition.indexOf("filename=") + x; int endIndex = contentDisposition.length() - i; return contentDisposition.substring(beginIndex, endIndex); } } Notation that we need to apply the @MultipartConfignote for this servlet course like this:
@MultipartConfig( fileSizeThreshold = 1024*1024*2, // 2MB maxFileSize = 1024*1024*ten, // 10MB maxRequestSize = 1024*1024*11 // 11MB )
You lot can alter the values accordingly, based you your awarding'southward need. The fileSizeThreshold value specifies the threshold across 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 Bulletin JSP Page
Equally you lot can come across in the doPost() method of the FileUploadServlet class in a higher place, it e'er redirects users to a JSP folio named message.jsp - to show successful bulletin or error message. Then create the message.jsp file under WebContent (webapp) with the following HTML code in the body:
<trunk> <div align="center"> <div><h3>${message}</h3></div> </div> </body> It simply prints the value of an attribute named message, which set in the servlet class above.
6. Test Uploading Files to Amazon S3
Now, y'all tin run the project in Eclipse by deploying information technology on Apache Tomcat server. Follow this video if you don't know how. And then access the application'due south home page at this URL:
http://localhost:8080/S3FileUploadExample/
The upload course should appear as shown below:
Enter some text into description field, and cull a file. Then click Submit. Wait a moment. If everything is going smoothly, you lot should meet the message page:
Now, sign in your AWS account. Get to S3 service, get in the saucepan you specified in the lawmaking. Be certain that the file exists there.
That'south my tutorial about coding S3 file upload functionality in a Java web awarding based on Servlet and JSP. To see the coding in activeness, I recommend you watch the following video:
Y'all can also download the sample projection attached below.
Related AWS Java SDK Tutorials:
- How to Generate AWS Access Primal ID and Secret Access Key
- How to setup AWS SDK for Coffee for Amazon S3 Evolution
- AWS Coffee SDK S3 Listing Buckets Example
- AWS Java SDK S3 Listing Objects Examples
- AWS Coffee SDK S3 Create Saucepan Examples
- AWS Java SDK S3 Create Folder Examples
- Upload File to S3 using AWS Jav SDK - Java Console Program
- Spring Kick File Upload to Amazon S3 Example
- AWS Java SDK Download File from S3 Example
- AWS Coffee SDK S3 Delete Objects Examples
- AWS Java SDK S3 Delete Buckets Examples
About the Author:
Nam Ha Minh is certified Coffee developer (SCJP and SCWCD). He started programming with Java in the time of Coffee 1.4 and has been falling in love with Java since and so. Brand friend with him on Facebook and sentinel his Java videos y'all YouTube.
Source: https://www.codejava.net/aws/upload-file-to-s3-java-servlet-jsp
0 Response to "How to Upload Xml File to Aws S3 Java Sdk"
Post a Comment