Java File Upload to a Folder
The File plays a vital role in each programming language. In order to work with File, every developer should have knowledge of how we can implement the file upload functionality in Java or other programming languages.
In this section, we will learn about how we can implement the file upload functionality in Java and will also understand how to upload a file to a folder.
In Java, we use a single servlet and an HTML form for creating a file upload request to the servlet. We implement a Simple HTML form having two fields, i.e., File and Destination. The input field of type File allows the user to browse the File from the system. After selecting the File from the system, we send the File as a POST request to the server. We add two restrictions to the form, i.e., encrypt="multipart/form-data" and method="POST".
With this restriction, the request sends to the server in the encoded form. The servlet handles the POST request, process the incoming file data, and extract File from the stream. The destination defines the path of the location where we need to save the File in the system. The data is posted to the servlet, and it stores the File to the specified location when we click on the Upload button.
The code of the HTML form is as follows:
POST and GET are the two methods that we can use at the time of submitting the form. Here, when we submit the form, the browser streams the content by combining all the parts. Each part defines the field of a form.
In the above code, we use two annotations, i.e., @WebServlet having properties name and urlPatterns, and @MultipartConfig.
The @WebServlet and the @MultipartConfig annotation are used for defining servlet mappings and for indicating that the servlet expects those requests which are made using the multipart/form-data MIME type, respectively.
The servlet performs the following steps to store file data into the destination folder:
In order to build, package, deploy and run the file upload program, we can either use NetBeans, Eclipse, or Ant. For NetBeans, we use the following steps:
Now, we navigate to the browser and enter the following URL:
After entering the URL and hit the enter key, the HTML form will open, which we create above. We browse the system and select a file to upload it to the desired location. In the destination field, we enter the path of the directory where we need to store that File. The directory should already be created in the system and must be writable. If we set nothing to the destination field and click on the upload button, it will throw an exception.
When we click on the upload button, a POST request send to the servlet, and it will copy the File to the destination folder.
After click on the upload button, we go to the specified directory and verify whether the uploaded File is present or not.
Next TopicJava Full Stack