Solved

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

Posted on 2004-08-06
10
1,909 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
ID: 11733787
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
ID: 11733799
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
ID: 11733954
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
ID: 11733983
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
ID: 11734025
Thank again sir. it helps me so much. i hope you could answer me again the next time i post a question. thanks!
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 35

Expert Comment

by:TimYates
ID: 11734035
No worries :-)

Glad I could help!

Good luck with it!!

Tim
0
 
LVL 35

Expert Comment

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

Author Comment

by:jemrusalem07
ID: 11734060
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
ID: 11734086
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
ID: 11750087
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Struts tiles for layout structure along with Angular JS. 4 150
Getting NoSuchMethodError on accessing a spring mvc project 3 158
struts exact match support 3 51
java operators 3 110
When we talk about DevOps toolchains, I sometimes wonder how many people really get what we’re talking about. I don’t know if it’s just semantics or tone or something else, but sometimes I think it just sounds like buzzword sausage. So it’s always …
Note: This is the third blog post in a series on email clearinghouses (https://www.xmatters.com/alert-management/blog-email-has-failed-us?utm_campaign=70138000000ydLoAAI&utm_source=exex&utm_medium=article&utm_content=blog-post).   We’ve been talki…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

932 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