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.
|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.
To upload the file to the server, there are two requirements:
- You must use the post request.
- encodeType should be multipart/form-data that gives information to the server that you are going to upload the file.
We are uploading the incoming file to the location d:/new, you can specify your location here.
<%@ page import="com.oreilly.servlet.MultipartRequest" %> <% MultipartRequest m = new MultipartRequest(request, "d:/new"); out.print("successfully uploaded"); %>
If size of the file is greater than 1MB, you should specify the post size.
Leave A Comment