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 I converted a table in an email to a graph on a website? Hint: Azure Functions and Logic App

This mini-project started as a necessity.  I get an email like this everyday, which gives daily numbers for different metrics. The problem with such an email is that it is difficult to keep track of or gauge the rate of growth of these metrics. If you want to know how what the previous day's numbers were you need to go to the previous day's email.  The better option any day is to have a graph that shows the values of the metrics every day. Something like this: With this goal I set out to make this system but with as less coding and expenses as possible.  First obvious step in the process was to get hold of the email and extract its text. The easiest way to do this is to use Azure Logic App.  Here is what my logic app looks like: When any new email arrives in my Outlook 365 account, with a subject that contains "System usage Stats as on", it passes the body of the email to an Azure function named 'EmailTextCleanerFunction' (code below), whose job is to clean an...

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!

Hands on review: Yahoo! Mail app for Windows 8

Before you start mocking me for using Yahoo! Mail, let me explain that this is NOT my primary mail account and I use Gmail and Outlook.com for my daily use. Yes, this Yahoo! account was once my daily haunt but that was during college days and those days are long gone. I don't use Yahoo! Mail much but still there are some group subscriptions and I just log in once in a while to see what's happening in those forgotten groups. And due to this reason, I have always kept track of changes in Yahoo! Mail and the fact is that you can blame them for everything but not really lack of trying. Though most of those tries just ended up cluttering the UI and adding somewhat needless features. However, now we hear that new CEO Marissa Mayer is focusing once again on the mail and first major product to come out is Yahoo! Mail app for Windows 8. So how is it? The Login screen is pretty neat and purple background with an envelope watermark is very pleasing, very Yahoo!. However why ...