Railo Aws Java Sdk Uploading Pdf File
- Details
- Written past
- Final Updated on 03 January 2022 | Print Email
In this AWS S3 Java SDK tutorial, I'd similar to guide you through the development of a Java web awarding based on Servlet & JSP, which allows users to upload files from their local computer, and so the files will be transferred to a bucket on Amazon S3 server. Information technology would exist transparent to the stop users, for the purpose of hosting static resources in a cloud storage service like S3.
The following picture explains the workflow of files uploaded to Amazon S3:
As you tin can see, a file will be uploaded 2 times. Firstly, it is transferred from the user's computer to the application server (e.chiliad. Apache Tomcat) which hosts the Coffee web app, which transfers the file to a bucket on S3 server programmatically using AWS SDK for Java. That means 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 Java for S3.
Software programs required: Java Development Kit (JDK), Apache Tomcat nine.0 server, Eclipse IDE.
1. Setup Java Web Maven project
In Eclipse IDE, create a Java Dynamic Web projection, and and then 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>2.15.0</version> <type>pom</blazon> <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.1</version> <scope>provided</telescopic> </dependency> </dependencies> </project>
Every bit you can come across, at least 2 dependencies required: S3 and Java Servlet.
two. Code File Upload Form
Side by side, let'due south code a JSP page that allows the finish users to pick a file from their local computer. Create the upload.jsp file nether 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-information"> <p>Description: <input blazon="text" name="description" size="xxx" required /></p> <p><input type="file" name="file" required /></p> <p><button type="submit">Submit</push></p> </form> </div>
The file upload folio would expect similar this in spider web browser:
Here, on this grade, nosotros can blazon some description text and choose a file to be uploaded.
3. Code S3 Utility class
Next, code a utility class that implements code for uploading a file to a bucket on Amazon S3 server, using S3 API provided past the AWS SDK. Here's the lawmaking:
parcel cyberspace.codejava.aws; import java.io.IOException; import coffee.io.InputStream; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.cadre.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 final Cord BUCKET = "your-bucket-proper name"; public static void uploadFile(String fileName, InputStream inputStream) throws S3Exception, AwsServiceException, SdkClientException, IOException { S3Client customer = S3Client.architect().build(); PutObjectRequest asking = PutObjectRequest.builder() .bucket(BUCKET) .key(fileName) .acl("public-read") .build(); client.putObject(request, RequestBody.fromInputStream(inputStream, inputStream.available())); } }
The code is pretty simple and straightforward. Y'all 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 will be stored in S3 with public-read permission, meaning that information technology is accessible to anybody - which is suitable for hosting public static resource (images, JS, CSS, …). If y'all want to keep the files private, do not use the acl() method.
Wait 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 yous desire to run some logics that depend on the being of the file on S3, consider calculation the following code:
S3Waiter waiter = customer.waiter(); HeadObjectRequest waitRequest = HeadObjectRequest.builder() .bucket(BUCKET) .primal(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 return when the file exists on S3 (uploaded completely).
Fix additional data for the upload file:
You can use the contentXXX() methods of the PutObjectRequest class to specify boosted information for the file stored on S3. For example, the following lawmaking fix content blazon of the file to be "image/png" for the file:
PutObjectRequest asking = PutObjectRequest.architect() .bucket(bucketName) .key(fundamental) .acl("public-read") .contentType("image/png") .build();
The other methods are contentDisposition(), contentEncoding(), contentLanguage(), contentLength()…
four. Code File Upload Servlet Course
Next, lawmaking a Java servlet course that handles submission of the upload grade. Below is the code:
packet cyberspace.codejava.aws; import java.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.Part; @WebServlet("/upload") @MultipartConfig( fileSizeThreshold = 1024*1024*2, // 2MB maxFileSize = 1024*1024*10, // 10MB maxRequestSize = 1024*1024*xi // 11MB ) public grade FileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public FileUploadServlet() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String description = request.getParameter("description"); System.out.println("Description: " + description); Office filePart = request.getPart("file"); String fileName = getFileName(filePart); Organisation.out.println("File proper noun = " + fileName); String message = ""; try { S3Util.uploadFile(fileName, filePart.getInputStream()); bulletin = "The file has been uploaded successfully"; } catch (Exception ex) { message = "Fault uploading file: " + ex.getMessage(); } request.setAttribute("message", message); request.getRequestDispatcher("message.jsp").forward(asking, response); } private String getFileName(Part function) { String contentDisposition = part.getHeader("content-disposition"); int beginIndex = contentDisposition.indexOf("filename=") + x; int endIndex = contentDisposition.length() - one; return contentDisposition.substring(beginIndex, endIndex); } }
Annotation that we 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*11 // 11MB )
You can change the values accordingly, based you lot your application's need. The fileSizeThreshold value specifies the threshold beyond which the file volition be stored on deejay temporarily (otherwise the file is stored in retentivity); maxFileSize is the maximum of the file which users can upload per request; maxRequestSize is the total size of a HTTP request, including form information.
5. Lawmaking Message JSP Folio
As yous tin can see in the doPost() method of the FileUploadServlet class above, it always redirects users to a JSP page named message.jsp - to show successful bulletin or error bulletin. So create the message.jsp file nether WebContent (webapp) with the post-obit HTML code in the body:
<body> <div align="center"> <div><h3>${message}</h3></div> </div> </torso>
It simply prints the value of an aspect named message, which fix in the servlet class above.
6. Examination Uploading Files to Amazon S3
At present, you tin run the project in Eclipse by deploying information technology on Apache Tomcat server. Follow this video if you don't know how. So access the awarding's dwelling page at this URL:
http://localhost:8080/S3FileUploadExample/
The upload form should appear equally shown below:
Enter some text into description field, and choose a file. Then click Submit. Expect a moment. If everything is going smoothly, you lot should encounter the message page:
Now, sign in your AWS account. Go to S3 service, become in the bucket yous specified in the code. Exist certain that the file exists in that location.
That's my tutorial about coding S3 file upload functionality in a Java spider web awarding based on Servlet and JSP. To see the coding in action, I recommend you lot watch the following video:
You can also download the sample projection fastened below.
Related AWS Java SDK Tutorials:
- How to Generate AWS Access Key ID and Secret Access Key
- How to setup AWS SDK for Java for Amazon S3 Development
- AWS Java SDK S3 List Buckets Instance
- AWS Coffee SDK S3 List Objects Examples
- AWS Java SDK S3 Create Bucket Examples
- AWS Coffee SDK S3 Create Folder Examples
- Upload File to S3 using AWS Jav SDK - Java Console Plan
- Spring Boot File Upload to Amazon S3 Instance
- AWS Java SDK Download File from S3 Example
- AWS Java SDK S3 Delete Objects Examples
- AWS Coffee SDK S3 Delete Buckets Examples
Virtually the Author:
Nam Ha Minh is certified Coffee programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in beloved with Coffee since and so. Make friend with him on Facebook and lookout his Coffee videos you YouTube.
Source: https://mail.codejava.net/aws/upload-file-to-s3-java-servlet-jsp
Post a Comment for "Railo Aws Java Sdk Uploading Pdf File"