How to pass parameter in multipart post request

Viewed 12245

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?

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

Related