Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

Uploading file

Here, we will learn how to upload file to the server. For uploading a file to the server, method must be post and enctype must be multipart/form-data in html file. For Example:

  1. <html>
  2. <body>
  3. <form action=“go” method=“post” enctype=“multipart/form-data”>
  4. Select File:<input type=“file” name=“fname”/><br/>
  5. <input type=“submit” value=“upload”/>
  6. </form>
  7. </body>
  8. </html>

Example of uploading file to the server in servlet

Now, for uploading a file to the server, there can be various ways. But, I am going to use MultipartRequest class provided by oreilly. For using this class you must have cos.jar file. If you will download this example, we will the cos.jar file alongwith code.

  1. import*;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.http.*;
  4. import com.oreilly.servlet.MultipartRequest;
  5. public class UploadServlet extends HttpServlet {
  6. public void doPost(HttpServletRequest request, HttpServletResponse response)
  7.     throws ServletException, IOException {
  8. response.setContentType(“text/html”);
  9. PrintWriter out = response.getWriter();
  10. MultipartRequest m=new MultipartRequest(request,“d:/new”);
  11. out.print(“successfully uploaded”);
  12. }
  13. }

There are two arguments passed in MultipartRequest class constructor, first one is HttpServletRequest object and second one is String object (for location). Here I am supposing that you have new folder in D driver.

web.xml file

This configuration file provides information about the servlet.

  1. <web-app>
  2. <servlet>
  3. <servlet-name>UploadServlet</servlet-name>
  4. <servlet-class>UploadServlet</servlet-class>
  5. </servlet>
  6. <servlet-mapping>
  7. <servlet-name>UploadServlet</servlet-name>
  8. <url-pattern>/go</url-pattern>
  9. </servlet-mapping>
  10. </web-app>