A JSP can be used with an HTML form tag to allow users to upload files to the server. An uploaded file can be a text file or a binary or an image file or just any document. 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.
It is a utility class to handle the multipart/form-data request. There are many constructors defined in the MultipartRequest class.
1. MultipartRequest(HttpServletRequest request, String saveDirectory) uploads the file upto 1MB.
2. MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize) uploads the file upto specified post size.
3. MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize, String encoding) uploads the file upto specified post size with given encoding.
To upload a file on server we can make use of <form> tag. It can be written as follows:
Following are the important points to be noted down −
1. The form method attribute should be set to POST method and GET method can not be used.
2. The form enctype attribute should be set to multipart/form-data.
3. The form action attribute should be set to a JSP file which would handle file uploading at backend server. Following example is using uploadFile.jsp program file to upload file.
4. To upload a single file you should use a single <input .../> tag with attribute type = "file". To allow multiple files uploading, include more than one input tag with different values for the name attribute. The browser associates a Browse button with each of them.
Here we have doPost() method in IconUpload.java, which will be called as we are passing POST method in JSP and it will have request and response objects as its parameters.
1. First set the type of response we will get after processing this request using response.setContentType().
2. Extract file name and define paths to save the file to be uploaded. This is done in extractFileName() below.
3. Within the try and catch block very simple work is done. Basically, an instance of PrintWriter writes the file content byte by byte and saves it to the specified location at server.
4. Redirect it to next page using response.sendRedirect().
And there you go!!