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

Posted on 2004-09-23
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2

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 440 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) iter.next();

    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();


What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article lists the top 5 free OST to PST Converter Tools. These tools save a lot of time for users when they want to convert OST to PST after their exchange server is no longer available or some other critical issue with exchange server or impor…
If you're a modern-day technology professional, you may be wondering if certifications are really necessary. They are. Here's why.
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

765 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