The resolution of the null problem when Request.getparameter () value is the enctype= "Multipart/form-data" of the form

Source: Internet
Author: User

Resolves a method that request.getparameter () gets no value when the form's enctype= "Multipart/form-data"


Today in the original upload file page on the basis of a file to add a brief introduction

Because at the same time upload files, so enctype= "multipart/form-data" must be added to the form inside

But in that case, I'm going to use the Request.getparameter () method in the servlet to just get the null value anyway,

Not generally depressed, Baidu a bit, some people have the same problem but it is used Jspsmartupload component implementation file upload,

And I used the Commons FileUpload component, a careful look at the API of this component, but the English is too bad, did not find the relevant information

I tried to pass the arguments with the session, but it was a bit of a hassle because when the form was submitted, you had to assign it to its value on the session form.

It seems to be JavaScript, but I don't,

Then only Google, search some Chinese web pages, also did not find information, try not to limit the language, hehe, a large, and then I sent

This is it.

I cannot read the submitter using Request.getparameter ("Submitter") (it returns null). ]

Situation:javax.servlet.HttpServletRequest.getParameter (String) returns NULL when the ContentType is multipart/ Form-data


Solution a:1. Download HTTP://WWW.SERVLETS.COM/COS/INDEX.HTML2. Invoke GetParameters () on Com.oreilly.servlet.MultipartRequest

Solution b:1. Download HTTP://JAKARTA.APACHE.ORG/COMMONS/SANDBOX/FILEUPLOAD/2. Invoke Readheaders () in Org.apache.commons.fileupload.MultipartStream

Solution c:1. Download HTTP://USERS.BOONE.NET/WBRAMELD/MULTIPARTFORMDATA/2. Invoke GetParameter on Com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:use Struts. Struts 1.1 handles this automatically. Say is not detailed, then look down, another solution >

Solution B:
> 1. Download >
> 2. Invoke Readheaders () in
> Org.apache.commons.fileupload.MultipartStream

The Solution B as given by our dear friend is a bit hectic and a bit complex:(
We can try the following solution which I found much simpler (at least in usage).

1. Download one of the versions of UploadFile from
2. Invoke parserequest (Request) on Org.apache.commons.fileupload.FileUploadBase which returns list of Org.apache.commons.fileupload.FileItem objects.
3. Invoke Isformfield () on each of the Fileitem objects. This determines whether the "file item is" a form paramater or stream of uploaded file.
4. Invoke getfieldname () to get parameter name and getString () to get parameter value on Fileitem if it ' s a form parameter . Invoke Write ( on Fileitem to save the uploaded file stream to a file if the Fileitem are not a form parameter.

Another way is to use the enctype= "Multipart/form-data" in the Jspsmartupload form to set the MIME encoding of the form. By default, this encoding format is application/x-www-form-urlencoded and cannot be used for file uploads, and only multipart/form-data can be used to complete the delivery of file data.

However, the enctype= "Multipart/form-data" is set, except that the file type form is available, and other value is not available through Request.getparameter. In this case, we can use the component to solve the problem, such as using the Jspsmartupload component

Com.jspsmart.upload.SmartUpload su = new Com.jspsmart.upload.SmartUpload ();
Su.initialize (PageContext);
Su.service (request, response);
Su.settotalmaxfilesize (100000000);
Su.setallowedfileslist ("Zip,rar");
Su.setdeniedfileslist ("exe,bat,jsp,htm,html,,,");
Su.upload ();

String Name = Su.getrequest (). GetParameter ("name");
String type_id = Su.getrequest (). GetParameter ("TYPE");

by Su.getrequest (). GetParameter ("value"), it is OK, su.upload () seems to have to be placed in front, the test will be su.upload () after the fetch parameter is unsuccessful.

This article from Csdn Blog, reproduced please indicate the source:

About the blood-vomiting experience with parameters for uploading files with jspsmartupload controls


Forms for uploading data:

<form name= "Form1" method= "Post" action= "Servlet/upfile" enctype= "Multipart/form-data" >
<p> Please enter your mobile number </p>
<input type= "text" name= "Phone" value= "1234567890"/>
<p> Photo Upload (present in *.gif and *.jpg files only) </p>
<input type= "File" name= "File1"/>

<input type= "Submit" name= "submit" value= "· Submit • " />

The background servlet that was submitted

Smartupload su =new smartupload ();

Su.initialize (This.getservletconfig (), request, response);

String Realpath = This.getservletcontext (). Getrealpath ("");
String path=realpath+ "/images";

Su.setallowedfileslist ("gif,jpg");
Su.upload ();
int (path);

Msdnid=su.getrequest (). GetParameter ("Phone");/note This is the parameter that receives the table conveys.
System.out.println ("msdnid=" +msdnid);

/////////////////////////////////////////////////////////////////////////////////////////////////////////////// /

Special NOTE: The statement used to receive form parameters must be placed in the Su.upload (), after the statement, that is, to receive the file after the upload, otherwise

No matter how you try to receive the result is always "null".

This is the 2 minutes I tried to get out of the day before I fainted, it's really not easy!!!!!

After the above problems are solved, when the transmitted parameters are Chinese characters are all garbled, after repeated experiments on the form page encoding format to "gb2312" to solve the problem.

This article from Csdn Blog, reproduced please indicate the source:

Solve a method that does not get other parameter values when the form's enctype= "Multipart/form-data"?

Prerequisite: Using Commons-fileupload-1.1.jar

Uploadlistener listener = new Uploadlistener (request, 0);
Create a factory for disk-based file items
Fileitemfactory factory = new Monitoreddiskfileitemfactory (listener);

Create a new file upload handler
Servletfileupload upload = new Servletfileupload (factory);

Process uploads.
List fileitems=upload.parserequest (Request);
Iterator iter = Fileitems.iterator (); Process each control in turn
while (Iter.hasnext ()) {
Fileitem item = (Fileitem) ();//ignore any other form information that is a file field
if (Item.isformfield ()) {
Out.println (Item.getfieldname () + "=" +item.getstring ()); Get form data
}catch (Fileuploadexception e) {
E.printstacktrace ();

This article from Csdn Blog, reproduced please indicate the source:

Enctype= of Form form "Multipart/form-data" experience Collection
When you use a form to transfer data, if the form adds the enctype= "Multipart/form-data" attribute, the form request is passed to another JSP or servlet
It is not possible to use Request.getparameter () to get the values of individual form elements.
This can be done universally (the API provided by the upload component):
Boolean ismultipart = servletfileupload.ismultipartcontent (request);
if (Ismultipart) {
Create a factory for disk-based file items
Org.apache.commons.fileupload.FileItemFactory factory = new Diskfileitemfactory ();
Create a new file upload handler
Servletfileupload upload = new Servletfileupload (factory);
Parse the request
List/* Fileitem */items = upload.parserequest (request);
Process the uploaded items
Iterator iter = Items.iterator ();

while (Iter.hasnext ()) {
Org.apache.commons.fileupload.FileItem item = (Org.apache.commons.fileupload.FileItem) ITER
. Next ();
if (Item.isformfield ()) {
String name = Item.getfieldname ();
String value = item.getstring ("GBK");
OUT.PRINTLN (name + "=" + value);
Params.put (Name.touppercase (), Value.trim ());
} ......
When using Multipart/form-data upload, the request sent is not the same as the normal HTTP, which requires conversion before other parameters can be read.

If you use spring, it provides a multirequestresolver that only requires:
Multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request;
Then you can read the parameters normally:
Multipartrequest.getparameter ("xxx");

Here's how spring is handled and you must first install the Commons-fileupload component:

Public multiparthttpservletrequest Resolvemultipart (HttpServletRequest request) throws Multipartexception {
Diskfileupload fileupload = this.fileupload;
String enc = determineencoding (request);

Use prototype FileUpload instance if the request specifies
Its own encoding so does not match the default encoding
if (!enc.equals (this.defaultencoding)) {
FileUpload = new Diskfileupload ();
Fileupload.setsizemax (This.fileUpload.getSizeMax ());
Fileupload.setsizethreshold (This.fileUpload.getSizeThreshold ());
Fileupload.setrepositorypath (This.fileUpload.getRepositoryPath ());
Fileupload.setheaderencoding (ENC);

try {
List Fileitems = fileupload.parserequest (request);
Map parameters = new HashMap ();
Map multipartfiles = new HashMap ();
for (Iterator it = Fileitems.iterator ();   It.hasnext ();) {
Fileitem Fileitem = (fileitem) ();
if (Fileitem.isformfield ()) {
String value = null;
try {
Value = fileitem.getstring (ENC);
catch (Unsupportedencodingexception ex) {
Logger.warn ("Could not decode multipart item" + fileitem.getfieldname () +
"' with Encoding '" + Enc + "': Using Platform Default");
Value = Fileitem.getstring ();
String[] Curparam = (string[]) Parameters.get (Fileitem.getfieldname ());
if (Curparam = = null) {
Simple form Field
Parameters.put (Fileitem.getfieldname (), new string[] {value});
else {
Array of simple form fields
string[] Newparam = Stringutils.addstringtoarray (Curparam, value);
Parameters.put (Fileitem.getfieldname (), Newparam);
else {
Multipart file field
Commonsmultipartfile file = new Commonsmultipartfile (Fileitem);
Multipartfiles.put (File.getname (), file);
if (logger.isdebugenabled ()) {
Logger.debug ("Found multipart file [" + file.getname () + "] of size" + file.getsize () +
"Bytes with original filename [" + file.getoriginalfilename () + "], stored" +
File.getstoragedescription ());
/***** Note that parameters is the value of a field such as normal text *****/
return new Defaultmultiparthttpservletrequest (request, multipartfiles, parameters);
catch (Fileuploadbase.sizelimitexceededexception ex) {
throw new Maxuploadsizeexceededexception (This.fileUpload.getSizeMax (), ex);
catch (Fileuploadexception ex) {
throw new Multipartexception ("Could not parse multipart request", ex);
<form name= "UserInfo" method= "post" action= "first_submit.jsp" enctype= "Multipart/form-data" >
Set enctype= "Multipart/form-data" in the Form tab to ensure the correct encoding of the file is anonymously uploaded.
As follows:
&LT;TD height= "align=" "right" > Upload business License picture:</td>
<td><input type= "FILE" name= "UploadFile" size= "></td>"
You have to add Enctype= "Multipart/form-data".
The meaning of enctype= "Multipart/form-data" in the form is to set the MIME encoding of the form. By default, this encoding format is application/x-www-form-urlencoded and cannot be used for file uploads, and only the multipart/form-data can be used to complete the transfer of file data and perform the following actions.
enctype=/"multipart/form-data/" is the uploading of binary data; The value of the input in the form is passed in the form of 2.
The input value in the form is passed in 2, so the request is not worth it. In other words, if you add this code, the request will not succeed,
When you add a form value to a database, you use the following:
Smartupload su = new smartupload ()//New Smartupload Object
Su.getrequest (). Getparametervalues (); take the array value
Su.getrequest (). GetParameter (); Take a single parameter single value

This article from Csdn Blog, reproduced please indicate the source:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.