File Upload in JSP Servlet
Uploading files or images is a major task in a web application. No matter what programming language you are using PHP, Java, JavaScript, Python, JSP, or servlet. Through this article, you will learn how to upload files, images, or any kind of multipart/form-data in JSP and Servlet.
Uploading files is always challenging in JSP Servlet before Java EE 7. But Servlet 3.1 introduced Java file upload in a very efficient way. In this article, we will discuss that method.
In Java, there are two prior ways you can upload any kind of media file. Use a jar file which is Apache Common File Upload API library or write your own multipart code. In this post, we will focus on java core interfaces and methods to upload files. And another tutorial, we will discuss the open-source Apache Common File Upload API.
Before going to the code section, let’s describe the approach to file upload. I have seen many developers upload the file directly to the MySQL database using BLOB format. And I think it’s the worst practice. You can check this video to learn more details about why storing binary data in MySQL is a bad practice. So here we will upload files to a directory and store the file information in a MySQL data table.
Get the complete source code from GitHub.
JSP Page Design With HTML5 file input tags
Create an index.jsp page inside your web pages directory. Below is the source code you can copy and paste into your file. Here note that the form submission type is POST and the enctype is multipart/form-data. And this is the most important HTML attribute to submit file data or media files.
Creating UploadServlet with @MultipartConfig annotation
When you will create the servlet, it contains the doGet and doPost methods. As earlier we mentioned that the form submission type is POST. So, inside the doPost method, we will process our multipart/form-data. When we are sending multipart/form-data to our servlet, so we need to add @MultipartConfig annotation before the servlet class name. When you will add the annotation, the servlet will understand “Oh, I need to process complex form data that includes media files”. And finally, we will store the file inside your project “web/files/” directory. Below is the UploadServlet.java file code.
If you would love to watch the video, please check it out on our YouTube Channel. To give support please subscribe to the channel which is completely free of cost.