Tuesday 5 April 2016

UPLOADING FILE TO THE SERVER USING JSP

There are many ways to upload the file to the server. One of the way is by the MultipartRequest class. For using this class you need to have the cos.jar file. In this example, we are providing the cos.jar file alongwith the code.

MultipartRequest class

It is a utility class to handle the multipart/form-data request. There are many constructors defined in the MultipartRequest class.

Commonly used Constructors of MultipartRequest class

  • MultipartRequest(HttpServletRequest request, String saveDirectory) uploads the file upto 1MB.
  • MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize) uploads the file upto specified post size.
  • MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize, String encoding)uploads the file upto specified post size with given encoding.


Example of File Upload in JSP

In this example, we are creating two files only, index.jsp and fileupload.jsp.

index.jsp

To upload the file to the server, there are two requirements:
  1. You must use the post request.
  2. encodeType should be multipart/form-data that gives information to the server that you are going to upload the file.

  1. <form action="upload.jsp" method="post" enctype="multipart/form-data">  
  2. Select File:<input type="file" name="fname"/><br/>  
  3. <input type="image" src="MainUpload.png"/>  
  4. </form>  

upload.jsp

We are uploading the incoming file to the location d:/new, you can specify your location here.

  1. <%@ page import="com.oreilly.servlet.MultipartRequest" %>  
  2. <%  
  3. MultipartRequest m = new MultipartRequest(request, "d:/new");  
  4. out.print("successfully uploaded");  
  5.   
  6. %>  

Example of Downloading file from the server using JSP

In this example, we are going to download the jsp file. But you may download any file. For downloading the file from the server, you should specify the content type named APPLICATION/OCTET-STREAM.

index.jsp

This file provides a link to download the jsp file.

  1. <a href="download.jsp">download the jsp file</a>  

download.jsp

In this example, we are downloading the file home.jsp which is located in the e: drive. You may change this location accordingly.

  1. <%    
  2.   String filename = "home.jsp";   
  3.   String filepath = "e:\\";   
  4.   response.setContentType("APPLICATION/OCTET-STREAM");   
  5.   response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");   
  6.   
  7.   java.io.FileInputStream fileInputStream=new java.io.FileInputStream(filepath + filename);  
  8.             
  9.   int i;   
  10.   while ((i=fileInputStream.read()) != -1) {  
  11.     out.write(i);   
  12.   }   
  13.   fileInputStream.close();   
  14. %>   


No comments:

Post a Comment