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

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!

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...

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 ...