[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2004-09-23
6
Medium Priority
?
653 Views
Last Modified: 2008-02-01
experts,

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
ENCTYPE="multipart/form-data"
makes all the other parameters unaccessible by request.getParameter()?

thanks.

0
Comment
Question by:dodowoman
  • 3
  • 2
6 Comments
 

Author Comment

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

Accepted Solution

by:
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
upload.setSizeThreshold(yourMaxMemorySize);
upload.setSizeMax(yourMaxRequestSize);
upload.setRepositoryPath(yourTempDirectory);

// 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()) {
        processFormField(item);
    } else {
        processUploadedFile(item);
    }
}

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(...);
    item.write(uploadedFile);
} else {
    InputStream uploadedStream = item.getInputStream();
    ...
    uploadedStream.close();
}

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




Regards
Sudhakar

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12149261
0
 

Author Comment

by:dodowoman
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) {
                   e.printStackTrace();
         error = e.toString();
               }
         
Enumeration files = null;
 try{
           files = multi.getFileNames();
 }catch(Exception e)
         {
           e.printStackTrace();
         }

          String fileParam = null;
           try{
           while (files.hasMoreElements())
             fileParam = (String) files.nextElement();
             
         }catch(Exception e)
         {
           e.printStackTrace();
         }
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?
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12312877
THNKS MATE :)
0

Featured Post

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.

Question has a verified solution.

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

Microsoft Office Picture Manager was included in Office 2003, 2007, and 2010, but not in Office 2013. Users had hopes that it would be in Office 2016/Office 365, but it is not. Fortunately, the same zero-cost technique that works to install it with …
I came across an unsolved Outlook issue and here is my solution.
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses

868 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