September 28, 2011

Upload a text/binary file to the server using a Servlet

1) Create the UploadFile.html file in the WebContent folder of the web application.

<html>
<head>
<title>Upload File</title>
</head>
<body>

<form action="uploadServlet" enctype="multipart/form-data" method="post">
Specify a file to upload <br/>
<input type="file" name="datafile" size="40">
<br/>
<input type="submit" value="Upload">
</form>

</body>
</html>

2) Create the UploadServlet.java servlet class in the src folder of the web application.

package info.icontraining.servlets;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class UploadServlet extends HttpServlet {

   public void doPost(HttpServletRequest request, HttpServletResponse response) 
                     throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();
      String contentType = request.getContentType();
  
      if ((contentType != null) 
               && (contentType.indexOf("multipart/form-data") >= 0)) {

         DataInputStream in = new DataInputStream(request.getInputStream());

         InputStream is = request.getInputStream();
         int formDataLength = request.getContentLength();
   
         // copy incoming bytes into a byte array
         byte dataBytes[] = new byte[formDataLength];
         int byteRead = 0;
         int totalBytesRead = 0;

         while (totalBytesRead < formDataLength) {
            byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
            totalBytesRead += byteRead;
         } 

         // retrieve uploaded filename
         String file = new String(dataBytes);
         String saveFile = file.substring(file.indexOf("filename=\"") + 10);
         saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
         saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,
                                          saveFile.indexOf("\""));
   
         // clip off the file content
         int lastIndex = contentType.lastIndexOf("=");
         String boundary = contentType.substring(lastIndex + 1, 
                                          contentType.length());
         int pos;
         pos = file.indexOf("filename=\"");
         pos = file.indexOf("\n", pos) + 1;
         pos = file.indexOf("\n", pos) + 1;
         pos = file.indexOf("\n", pos) + 1;
         int boundaryLocation = file.indexOf(boundary, pos) - 4;
         int startPos = ((file.substring(0, pos)).getBytes()).length;
         int endPos = ((file.substring(0, 
                              boundaryLocation)).getBytes()).length; 

         String outputfile = this.getServletContext().getRealPath(saveFile);
         FileOutputStream os = new FileOutputStream (outputfile);

         os.write(dataBytes, startPos, (endPos - startPos));
         os.flush();
         os.close();

         out.println("You have successfully uploaded the file");
      }
   }
}

3) Configure the servlet in the web.xml deployment descriptor present in the WebContent/WEB-INF folder of the web application

<servlet>
   <servlet-name>uploadServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>uploadServlet</servlet-name>
   <url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>

4) Test the code with the following URL in the browser. The file will be uploaded to the context root (folder) of the web application.

http://localhost:8080/WebAppName/UploadFile.html

1 comment: