logo

Uploading File To The Server Using JSP


Show

There are many methods to upload the document to the server. One of the way is through the MultipartRequest class. For the use of this class, you want to have the cos.jar file. In this example, we're offering the cos.jar file along with the code.

MultipartRequest class

It is a utility class to address the multipart/form-information request. There are many constructors defined withinside the MultipartRequest class.

Commonly used Constructors of MultipartRequest class

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

Example of File Upload in JSP

We are generating two files only that is index.jsp and fileupload.jsp, in the below given example:

index.jsp

To upload the file to the server, there is two necessity:

  1. You must use the post request.
  2. encode type must be multipart/form-data that gives information to the server that you are going to upload the file.
<form action="upload.jsp" method="post" enctype="multipart/form-data">  
Select File:<input type="file" name="fname"/><br/>  
<input type="image" src="MainUpload.png"/>  
</form>

upload.jsp

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

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

If the size of the file is more than 1MB, you must define the post size.

download this example