Solved

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

Posted on 2004-08-06
10
1,922 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
VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

 
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

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
logging jar 1 110
Is it possible to "sandbox" html content within a JSP? 4 101
own marker interface 1 55
login jsp example 24 51
Data breaches are on the rise, and companies are preparing by boosting their cybersecurity budgets. According to the Cybersecurity Market Report (http://www.cybersecurityventures.com/cybersecurity-market-report), worldwide spending on cybersecurity …
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

832 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