Solved

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

Posted on 2004-08-06
10
1,933 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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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
 
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
best way to search/remove a file from an EAR file 3 112
Java Exception example issues 11 84
maven j2ee examles 2 60
servlet example 17 51
Is your phone running out of space to hold pictures?  This article will show you quick tips on how to solve this problem.
There's a lot of hype surrounding blockchain technology. Here's how it works and some of the novel ways it' s now being used - including for data protection.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

808 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