Solved

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

Posted on 2004-08-06
10
1,940 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Problem with Pie chart in Jsp 20 233
J2SE 5.0 metadata 1 67
session bean client machine 9 66
Handle form fields in spring mvc controller 1 70
Did you know that more than 4 billion data records have been recorded as lost or stolen since 2013? It was a staggering number brought to our attention during last week’s ManageEngine webinar, where attendees received a comprehensive look at the ma…
Although a lot of people devote their energy toward marketing for specific industries, there are some basic principles that can be applied to any sector imaginable. We’ll look at four steps to take and examine how those steps were put into action fo…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

685 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