Solved

JSP Upload and parameter passing : issue of enctype attribute of form element

Posted on 2004-08-06
10
1,893 Views
Last Modified: 2008-01-09
i have a tricky question sir, though im just new to servlet.

I have a jsp file that calls a servlet, i had managed to upload file fortunately

and i think i need to specify the enctype attribute of form element to

"multipart/form-data", to comply file upload. everything works to this point

in my servlet that downloads the file.

When i remember that i also need to pass the username in request parameter,

I add a text element in my jsp file, and when i try again

the upload still works but i always get a null value whenever i access the request parameter

finally i resolved to do something like this:

  enctype="multipart/form-data/application/x-www-form-urlencoded"

now i don't get null anymore when i access the username request parameter

but this time i got error when i try to upload a file.

what does enctype means? will it only choose one when it goes to the request object
and will not choose again if it already choose one?

OR CAN I CHANGE THE ENCTYPE OR CONTENTTYPE OF THE REQUEST OBJECT INSIDE SERVLET?

What should i do now sir/madam for me to read both file upload and string (object) value in request parameter?

here is part of my codes:

.jsp

<form name="form1"  enctype="multipart/form-data/application/x-www-form-urlencoded"  method="post" action="../servlet/Uploader.uploadRename" >

<input type="text" size="23" name="username" value="jemjem" >
<input type="file" accept="image/*" name=photo maxlength="50" size="50">
<input type="reset" value="Reset" name="Reset">
<input type="submit" name="mybutton" value="Upload Photo" onclick="return checkExt()" >
 
</form>

servlet
Note: IM USING ORIELLY PACKAGE HERE. THANKS.
 
 public void doPost ( HttpServletRequest req, HttpServletResponse res )
           throws ServletException, IOException
    {
        System.out.println(req.getContentType());

        String ngcId = (String) req.getParameter( "ngcId" );

         System.out.println("------------------> " + ngcId );

        MultipartRequest mpr = new MultipartRequest( req, path, 5*1024*1024);


THANKS IN ADVANCE FOR ANY HELP. I REALLY NEED THIS. THANKS.



0
Comment
Question by:jemrusalem07
  • 6
  • 4
10 Comments
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
From the example WAR file that you get with COS (DemoRequestUploadServlet.java)

----------------

/*

 * DemoUploadServlet.java

 *

 * Example servlet to handle file uploads using MultipartRequest for

 * decoding the incoming multipart/form-data stream

 */

 

import java.util.Enumeration;

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;



import com.oreilly.servlet.MultipartRequest;

import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;



public class DemoRequestUploadServlet extends HttpServlet {

  private String dirName;

 

  public void init(ServletConfig config) throws ServletException {

    super.init(config);

    // read the uploadDir from the servlet parameters

    dirName = config.getInitParameter("uploadDir");

    if (dirName == null) {

      throw new ServletException("Please supply uploadDir parameter");

    }

  }

 

  public void doPost(HttpServletRequest request, HttpServletResponse response)

      throws ServletException, IOException {

    PrintWriter out = response.getWriter();

    response.setContentType("text/plain");

    out.println("Demo Upload Servlet using MultipartRequest");

    out.println();

     

    try {

      // Use an advanced form of the constructor that specifies a character

      // encoding of the request (not of the file contents) and a file

      // rename policy.

      MultipartRequest multi =

        new MultipartRequest(request, dirName, 10*1024*1024,

                             "ISO-8859-1", new DefaultFileRenamePolicy());

       

      out.println("PARAMS:");

      Enumeration params = multi.getParameterNames();

      while (params.hasMoreElements()) {

        String name = (String)params.nextElement();

        String value = multi.getParameter(name);

        out.println(name + "=" + value);

      }

      out.println();

             

      out.println("FILES:");

      Enumeration files = multi.getFileNames();

      while (files.hasMoreElements()) {

        String name = (String)files.nextElement();

        String filename = multi.getFilesystemName(name);

        String originalFilename = multi.getOriginalFileName(name);

        String type = multi.getContentType(name);

        File f = multi.getFile(name);

        out.println("name: " + name);

        out.println("filename: " + filename);

        out.println("originalFilename: " + originalFilename);

        out.println("type: " + type);

        if (f != null) {

          out.println("f.toString(): " + f.toString());

          out.println("f.getName(): " + f.getName());

          out.println("f.exists(): " + f.exists());

          out.println("f.length(): " + f.length());

        }

        out.println();

      }

    }

    catch (IOException lEx) {

      this.getServletContext().log(lEx, "error reading or saving file");

    }

  }

}

0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
As you can see from this line:

      MultipartRequest multi =
        new MultipartRequest(request, dirName, 10*1024*1024,
                             "ISO-8859-1", new DefaultFileRenamePolicy());

you have to wrap the request up in a MultipartRequest object...  Then, you can do

      multi.getParameter( "ngcId" ) ;

Tim

PS:  Sorry for all the double spaced lines...
0
 

Author Comment

by:jemrusalem07
Comment Utility
Thank you very much sir Tim Yates. It worked as i wanted.
but before i closed the question.

what should i do if i'm not using the orielly package?

what should i do to change the content type? or atleast be flexible for this?

( i will grant u the points later sir, after any opinion you may further help me. thanks )



0
 
LVL 35

Accepted Solution

by:
TimYates earned 100 total points
Comment Utility
You need to use either;

1)  The com.oreilly.servlet package, OR the jakarta upload package...  This is becuase the Tomcat classes cannot handle Multipart form posts on their own.  And you cannot post a FILE object from an HTML page without using Multipart form posts (as you are now) :-(

2)  What do you mean change the content type?  It should work as it is:

<form name="form1"  enctype="multipart/form-data"  method="post" action="../servlet/Uploader.uploadRename" >
0
 

Author Comment

by:jemrusalem07
Comment Utility
Thank again sir. it helps me so much. i hope you could answer me again the next time i post a question. thanks!
0
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 35

Expert Comment

by:TimYates
Comment Utility
No worries :-)

Glad I could help!

Good luck with it!!

Tim
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
Hehe, maybe next time I can get an "A" grade rather than a "B" :-(
0
 

Author Comment

by:jemrusalem07
Comment Utility
oops im sorry sir. i thought its nothing, so i just clicked one. i thought what's only important is the points after all. next time i will remember. thanks
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
Hee hee, no worries ;-)

(it's the morning, and I'm always grumpy in the morning) ;-)

What happens is that by selecting A, B or C, you multiply the number of points I recieve for answering your question :-)

For a 100 point question, "A" gives me 400 expert points, "B" gives me 300, and "C" gives me 100

It still costs you only 100 points, but I get more expert points depending on the grade :-)

Heheh..just so you know for future reference :-)

Again, good luck with your project!! :-)

Tim
0
 

Author Comment

by:jemrusalem07
Comment Utility
good am sir.

could u also help me how to get the request parameter BEFORE i use the Oreilly Upload?

THANKS AGAIN.
0

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

Describes a method of obtaining an object variable to an already running instance of Microsoft Access so that it can be controlled via automation.
Restoring deleted objects in Active Directory has been a standard feature in Active Directory for many years, yet some admins may not know what is available.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

772 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

11 Experts available now in Live!

Get 1:1 Help Now