How to upload a file to server
We can use html form's file control to upload a file to server end.
This is not a simple process as form data is not a simple data but the
form data must be set to enctype="multipart/form-data" and method must
be set to POST.
One simple form may be like follows
<form name="form1" action="/uploader.htm" method="post" enctype="multipart/form-data">
<input class="fileUploadInput" type="file" name="file">
<input type="submit" value="Upload">
</form>
At Server end we can use one of several possible wrappers available for
file upload. One I will use here for demonstration is very popular library
provided by jakarta commons file upload library. It's jar commons-fileupload.jar
can be downloaded from site http://commons.apache.org/fileupload/.
I will write a code to process the request's data to extract file content from
uploaded form data. Since the data is of multipart in nature, I will use a wrapper
for file data given by commons file upload library.
Suppose you are given an instance of HttpServletRequest named as request in your servlet context.
You can use it to parse the file data as follows
String UPLOAD_DIR = "/uploadDir";
DiskFileUpload diskFileUpload = new DiskFileUpload();
diskFileUpload.setSizeMax(1000000);
List
for (FileItem fileItem : fileItems) {
if (fileItem != null) {
if (!fileItem.isFormField()) {
File file = new File(UPLOAD_DIR + File.separator + fileItem.getName());
fileItem.write(file);
}
} else {
System.out.println("File Item is null. Kindly Check it.");
}
}
This code when executed will save a file to /uploadDir location.
First of all we created a DiskFileUpload instance and then it's size was set to 1 MB.
Then request instance was parsed to create a list of FileItems. Each FileItem represents
a single form field. It may be a File Field or it may be a simple form field such as
a input type or it may be a button etc. So to parse the file type we need to put a check if
this is not a form field (or it is a file type field), this is done using the inner if
clause. If this is of type file then a new File instance is created using the name of
fileName.getName(); and then the file is written to the UPLOAD_DIR.