Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter in multipart post request

Servlet code

request.getparameter("fname") //I can't able to get value.

HTML code

 <html>
    <head>
    <title>File Uploading Form</title>
    </head>
    <body>
    <h3>File Upload:</h3>
    Select a file to upload: <br />
    <form action="UploadServlet" method="post"
                            enctype="multipart/form-data">
    <input type="text" name="fname" size="50" />   
 <input type="file" name="file" size="50" />
 <input type="submit" value="Upload File" />
    </form>
    </body>
    </html>  

My question is : How to pass fname parameter in multipart post request?

like image 635
Jeevan Roy dsouza Avatar asked Dec 05 '13 07:12

Jeevan Roy dsouza


People also ask

How do you pass a parameter in multipart form data?

You should use request. getparameter("fname"). Maybe action is UploadServlet.

How do you use multipart form data?

Multipart form data: The ENCTYPE attribute of <form> tag specifies the method of encoding for the form data. It is one of the two ways of encoding the HTML form. It is specifically used when file uploading is required in HTML form. It sends the form data to server in multiple parts because of large size of file.


1 Answers

Short answer: you will find the fname in the Parts of the request.

Long answer: For multipart type requests, even the simple <input type="text"> field values are placed in parts. You will have to iterate over the Part objects returned by HttpServletRequest.getParts() and handle them according to their name property:

for( Part p : request.getParts() ) {
    if( "fname".equals(p.getName()) ) {
        ...
    }
    else if( "file".equals(p.getName()) ) {
        ...
    }
}

To complicate things further, the content of the part is available as InputStream - Part.getInputStream() - so you will have to do a little transforming stream → byte[]String to get the value.

like image 134
Nikos Paraskevopoulos Avatar answered Oct 08 '22 05:10

Nikos Paraskevopoulos