Servlet – Uploading File

Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver.
Now let us learn how to upload a file to a server in this section. In an HTML file, the method must be posted and the enctype must be multipart/form-data when uploading a file to the server.
Creating a File Upload Form
- The following HTML code below creates an uploader form. The following are some key factors to remember:
 - The form method should be set to POST, and the GET method should not be utilized.
 - The multipart/form-data enctype property should be used.
 - Set the form action property to a servlet file that will handle file uploading on the backend server. To upload a file, the following example uses the UploadServlet servlet.
 - To upload a single file, use a single <input…/> element with the type=”file” attribute. Include several input tags with distinct names for the name attribute to allow various files to be uploaded. Each of them has a Browse button associated with it in the browser.
 
Implementation:
Step 1: We will create a dynamic web project in Eclipse and the project structure will look like the below image.
Remember: There are several options for uploading a file to the server. However, we are going to utilize O’Reilly’s MultipartRequest class. We will need the cos.jar file to use this class.
A. File: index.html
HTML
<html> <body> <form action="GoGfg" method="post" enctype="multipart/form-data"> Select File:<input type="file" name="fname"/><br/> <input type="submit" value="upload"/> </form> </body> </html>  | 
B. File: GfgFileUpload.java
Make sure you have created directories C:\\temp (it is with reference to Windows operating systems)
Example:
Java
// Java Program to Illustrate File Uploading // Via Servlets// Importing required classesimport java.io.*;import javax.servlet.ServletException;import javax.servlet.http.*;import com.oreilly.servlet.MultipartRequest;// Class// Extending HttpServlet classpublic class GfgFileUpload extends HttpServlet {    // Method    // To handle request response mechanism    public void doPost(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {        response.setContentType("text/html");        PrintWriter out = response.getWriter();        MultipartRequest m = new MultipartRequest(request, "C:\\temp");        out.print("File uploaded successfully");    }} | 
C. File: web.xml
XML
<?xml version="1.0" encoding="UTF-8"?><web-app><servlet>   <servlet-name>GfgFileUpload</servlet-name>   <servlet-class>GfgFileUpload</servlet-class></servlet><servlet-mapping>   <servlet-name>GfgFileUpload</servlet-name>   <url-pattern>/GoGfg</url-pattern></servlet-mapping></web-app> | 
Output:
Step 2: After Clicking on the upload button file will be uploaded to the C:\\temp location
				
					



