Skip to main content

How to upload a file using JSP/Servlets

This short article describes how to upload a file using Apache Jakarta commons upload library.

1) Required downloads: Download the library from here. Keep the following JAR files in classpath: commons-fileupload-1.2.1.jar and commons-io-1.4.jar.

2) JSP/HTML code: To upload a file you need to set the encoding type in your form to multipart/form-data.




Give your users a file-select box to select the file :
input type="file" name="myFile" width="100"
You will most probably have other form fields like textbox, radio buttons etc. We have one text field with name 'user' in this form:
input maxlength="255" size="40" name="user"

3) Form data handling: Now you have sent the file and other form data, now we need to make use of this form data. Most probably you need to save the file at some location on the server.
One problem that many developers face is getting a null when they try to extract the value in form fields using request.getParameter(). So in our case, if you try doing this:
String user=request.getParameter("user");
you will find that 'user' has a null value.
But Apache Jakarta Commons Upload library gives us the way to overcome this problem also.
To handle the form data, I am using a servlet here. You may use a JSP, if you want, however that won't be a good design!

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

......
......
......
//Step 1: check if the request is a file upload request or not.
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//Step 2: parse the request.

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = new ArrayList();
try {
items = upload.parseRequest(request);
} catch (FileUploadException fue) {
fue.printStackTrace();
}
//Step 3:

Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
// I am saving the files in WEB-INF/images folder.
try {
String FOLDER = getServletContext().getRealPath("/WEB-INF");
String imgName= item.getName();
int last=imgName.lastIndexOf("\\");
imgName=imgName.substring(last+1,imgName.length());
FOLDER = FOLDER.replace("WEB-INF", "images/"+imgName);
if (FOLDER != null) {
FOLDER = FOLDER.replace('\\', '/'). replace('/', File.separatorChar);
}
File file = new File(FOLDER);

item.write(file);
qb.setImage(FOLDER);
} catch (Exception e) {
e.printStackTrace();
}
} else { //Handle the textual form data.
//Get the name of the field

String name = item.getFieldName();
//Get the value of the field

String value = item.getString();
System.out.println("Name=" + name + " value=" + value);

if(name.equals("user"))
System.out.println("User ="+value);
}
}
.....
.....
.....
}
This is all that you need to upload a file. See it was so simple!

Comments

AnilReddy Karna said…
in your code what is qb,and where the object is created

File file = new File(FOLDER);
item.write(file);
qb.setImage(FOLDER);
David James said…
Thanks a bunch for this...it was a life saver...!!!!

Popular posts from this blog

How to upload to Google Cloud Storage buckets using CURL

Signed URLs are pretty nifty feature given by Google Cloud Platform to let anyone access your cloud storage (bucket or any file in the bucket) without need to sign in. Official documentation gives step by step details as to how to read/write to the bucket using gsutil or through a program. This article will tell you how to upload a file to the bucket using curl so that any client which doesn't have cloud SDK installed can do this using a simple script. This command creates a signed PUT URL for your bucket. gsutil signurl -c 'text/plain' -m PUT serviceAccount.json gs://test_bucket_location Here is my URL: https://storage.googleapis.com/test_sl?GoogleAccessId=my-project-id@appspot.gserviceaccount.com&Expires=1490266627&Signature=UfKBNHWtjLKSBEcUQUKDeQtSQV6YCleE9hGG%2BCxVEjDOmkDxwkC%2BPtEg63pjDBHyKhVOnhspP1%2FAVSr%2B%2Fty8Ps7MSQ0lM2YHkbPeqjTiUcAfsbdcuXUMbe3p8FysRUFMe2dSikehBJWtbYtjb%2BNCw3L09c7fLFyAoJafIcnoIz7iJGP%2Br6gAUkSnZXgbVjr6wjN%2FIaudXIqA...

Running Apache Beam pipeline using Spark Runner on a local standalone Spark Cluster

The best thing about Apache Beam ( B atch + Str eam ) is that multiple runners can be plugged in and same pipeline can be run using Spark, Flink or Google Cloud Dataflow. If you are a beginner like me and want to run a simple pipeline using Spark Runner then whole setup may be tad daunting. Start with Beam's WordCount examples  which help you quickstart with running pipelines using different types of runners. There are code snippets for running the same pipeline using different types of runners but here the code is running on your local system using Spark libraries which is good for testing and debugging pipeline. If you want to run the pipeline on a Spark cluster you need to do a little more work! Let's start by setting up a simple standalone single-node cluster on our local machine. Extending the cluster is as easy as running a command on another machine, which you want to add to cluster. Start with the obvious: install spark on your machine! (Remember to have Java a...

Changing Eclipse Workspace Directory

Recently I moved my entire Eclipse installation directory but the workspace was still getting created in the older location only. And worst there was no option to select the Workspace directory in the Window->Options->Workspace menu. To change the workspace location in Eclipse do this. Goto ECLIPSE_HOME\configuration\.settings directory, edit the org.eclipse.ui.ide.prefs file and change the RECENT_WORKSPACES value to the desired location. If you want that Eclipse prompts you to select workspace when you start it, change the SHOW_WORKSPACE_SELECTION_DIALOG value to true. And you are done!