how to upload a file and update other fields on the jsp form page at the same time?

Posted on 2004-09-23
Last Modified: 2008-02-01

I have a jsp form which has a "browse" button and many other fields. THe idea is when user click on "submit", if there is a file entry in the "browse" button text field entry, then the file should be uploaded to the server, and any other changes on the form should also get pass to the database.
I use a ContollerServlet to handle all the request from form, and pass the request to other classes to process the request and finally pass the result to JSP pages.

I have successfully make s the form work without "browse" button. but when the "browse" button is added, the submit failed. my questions are:

1. is it possible to pass the "request" class from JSP to java class? Is the "request" on JSP page same as "HttpServletRequest " in servlet doPost()?
if both request are referring the same thing, why is the parameters on the form could not be passed to the java class, by using
request.getParameter() in the servlet? is it because I have to use the form tag like this one:
    <form action="<%=request.getContextPath()%>/servlet/ControlServlet?from=Upload" ENCTYPE="multipart/form-data" method="post" name="visits" onSubmit="return validate()" >

and the
makes all the other parameters unaccessible by request.getParameter()?


Question by:dodowoman
  • 3
  • 2
LVL 11

Expert Comment

ID: 12140063

Author Comment

ID: 12145135
thanks, but what is the advantage of using FileUpload class instead of using MultipartRequest class, do you know?
LVL 14

Accepted Solution

sudhakar_koundinya earned 110 total points
ID: 12149260
>>but what is the advantage of using FileUpload class instead of using MultipartRequest class, do you know?

It has much advantages over       MultipartRequest  class

Using FileUpload

FileUpload can be used in a number of different ways, depending upon the requirements of your application. In the simplest case, you will call a single method to parse the servlet request, and then process the list of items as they apply to your application. At the other end of the scale, you might decide to customize FileUpload to take full control of the way in which individual items are stored; for example, you might decide to stream the content into a database.

Here, we will describe the basic principles of FileUpload, and illustrate some of the simpler - and most common - usage patterns. Customization of FileUpload is described elsewhere .
How it works

A file upload request comprises an ordered list of items that are encoded according to RFC 1867 , "Form-based File Upload in HTML". FileUpload can parse such a request and provide your application with a list of the individual uploaded items. Each such item implements t he FileItem interface, regardless of its underlying implementation.

Each file item has a number of properties that might be of interest for your application. For example, every item has a name and a content type, and can provide an InputStream to access its data. On the other hand, you may need to process items differently, depending upon whether the item is a regular form field - that is, the data came from an ordinary text box or similar HTML field - or an uploaded file. The FileItem interface provides the methods to make such a determination, and to access the data in the most appropriate manner.

FileUpload creates new file items using a FileItemFactory . This is what gives FileUpload most of its flexibility. The factory has ultimate control over how each item is created. The default factory stores the item's data in memory or on disk, depending on the size of the item (i.e. bytes of data). However, this behavior can be customized to suit your application.
Parsing the request

Before you can work with the uploaded items, of course, you need to parse the request itself. Ensuring that the request is actually a file upload request is straightforward, but FileUpload makes it simplicity itself, by providing a static method to do just that.

// Check that we have a file upload request
boolean isMultipart = FileUpload.isMultipartContent(request);

Now we are ready to parse the request into its constituent items.
The simplest case

The simplest usage scenario is the following:

    * Uploaded items should be retained in memory as long as they are reasonably small.
    * Larger items should be written to a temporary file on disk.
    * Very large upload requests should not be permitted.
    * The built-in defaults for the maximum size of an item to be retained in memory, the maximum permitted size of an upload request, and the location of temporary files are acceptable.

Handling a request in this scenario couldn't be much simpler:

// Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload();

// Parse the request
List /* FileItem */ items = upload.parseRequest(request);

That's all that's needed. Really!

The result of the parse is a List of file items, each of which implements the FileItem interface. Processing these items is discussed below.
Exercising more control

If your usage scenario is close to the simplest case, described above, but you need a little more control over the size thresholds or the location of temporary files, you can customize the behavior using the methods of the DiskFileUpload class, like this:

// Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload();

// Set upload parameters

// Parse the request
List /* FileItem */ items = upload.parseRequest(request);

Of course, each of the configuration methods is independent of the others, but if you want to configure them all at once, you can do that with an alternate parseRequest() method, like this:

// Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload();

// Parse the request
List /* FileItem */ items = upload.parseRequest(request,
        yourMaxMemorySize, yourMaxRequestSize, yourTempDirectory);

Should you need further control over the parsing of the request, such as storing the items elsewhere - for example, in a database - you will need to look into customizing FileUpload.
Processing the uploaded items

Once the parse has completed, you will have a List of file items that you need to process. In most cases, you will want to handle file uploads differently from regular form fields, so you might process the list like this:

// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = (FileItem);

    if (item.isFormField()) {
    } else {

For a regular form field, you will most likely be interested only in the name of the item, and its String value. As you might expect, accessing these is very simple.

// Process a regular form field
if (item.isFormField()) {
    String name = item.getFieldName();
    String value = item.getString();

For a file upload, there are several different things you might want to know before you process the content. Here is an example of some of the methods you might be interested in.

// Process a file upload
if (!item.isFormField()) {
    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();

With uploaded files, you generally will not want to access them via memory, unless they are small, or unless you have no other alternative. Rather, you will want to process the content as a stream, or write the entire file to its ultimate location. FileUpload provides simple means of accomplishing both of these.

// Process a file upload
if (writeToFile) {
    File uploadedFile = new File(...);
} else {
    InputStream uploadedStream = item.getInputStream();

Note that, in the default implementation of FileUpload, write() will attempt to rename the file to the specified destination, if the data is already in a temporary file. Actually copying the data is only done if the the rename fails, for some reason, or if the data was in memory.

If you do need to access the uploaded data in memory, you need simply call the get() method to obtain the data as an array of bytes.

// Process a file upload in memory
byte[] data = item.get();


How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

LVL 14

Expert Comment

ID: 12149261

Author Comment

ID: 12164523
thanks, but I am trying to fix someone else's bug, where is using MultipartRequest class.
this is the codes, please help. i can't see the problem:
try {
      multi = new MultipartRequest(req, FILE_PATH, 500 * 1024
        , new com.oreilly.servlet.multipart.DefaultFileRenamePolicy());
      }catch (Exception e) {
         error = e.toString();
Enumeration files = null;
           files = multi.getFileNames();
 }catch(Exception e)

          String fileParam = null;
           while (files.hasMoreElements())
             fileParam = (String) files.nextElement();
         }catch(Exception e)
savedFileName = multi.getFilesystemName(fileParam);// get the saved file name

if (savedFileName!=null && savedFileName.length()>0)// if the file saved successfully

session.setAttribute("file", savedFileName);
else  session.setAttribute("file", "");
the file always return "null", and not throwing any exception.why?
LVL 14

Expert Comment

ID: 12312877

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
String format issue 13 88
session bean client machine 9 53
some methods private some are not 8 183
maven j2ee examles 2 43
Never store passwords in plain text or just their hash: it seems a no-brainier, but there are still plenty of people doing that. I present the why and how on this subject, offering my own real life solution that you can implement right away, bringin…
We have come a long way with backup and data protection — from backing up to floppies, external drives, CDs, Blu-ray, flash drives, SSD drives, and now to the cloud.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now