Convenient Way to Parse Incoming Multipart/Form-Data Parameters in a Servlet

Convenient way to parse incoming multipart/form-data parameters in a Servlet

multipart/form-data encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded encoding. When using a different encoding, the request.getParameter() calls will all return null. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts() instead. Also see this blog for extended examples.

Prior to Servlet 3.0, a de facto standard to parse multipart/form-data requests would be using Apache Commons FileUpload. Just carefully read its User Guide and Frequently Asked Questions sections to learn how to use it. I've posted an answer with a code example before here (it also contains an example targeting Servlet 3.0).

parse multipart/form-data request in a Servlet

First, reading a mime message from a servlet can be done using the standard HttpServletResponse methods getParameter("abc"). However to get the raw message, do as you have done and access the request body via the InputStream.

In JavaMail, the constructor to javax.mail.internet.MimeMessage contains a parameter for a mime-encoded InputStream. That should be able to parse the message for you.

How to parse multipart form-data using only EL

multipart/form-data is used to upload file. This could be big and uploading it could take a while. In order not to block other incoming requests the processing could be asynchronous.

With Java:

@MultipartConfig:

For a servlet receiving multipart/form-data you have to add the @MultipartConfig annotation in front of the servlet, in order to get the values of the plain text parameters by calling request.getParameter("notFileFieldName");. Otherwise the call will return null.

But with the file and its content, it didn't work this way.

The file name, content-type, size and content could be retrieved from the Part object returned by

request.getPart("theFileFieldName");

For JSP you can add the following snipplet in the web.xml:

<servlet>
<servlet-name>UploadFile</servlet-name>
<jsp-file>/path/form.jsp</jsp-file>
<multipart-config></multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>UploadFile</servlet-name>
<url-pattern>/path/form.jsp</url-pattern>
</servlet-mapping>

Where the line <multipart-config></multipart-config> activate the above behavior for the JSP.

So ${param.notFileFieldName} will be evaluated to its value.

But not the ${param.theFileFieldName}

AsyncContext could used to process the upload

  • Documentation
  • Tutorial

But you won't a java solution.

With Javascript: FileReader()

A basic example how you can read file on the client side. (without upload)
Source: https://developer.mozilla.org/de/docs/Web/API/FileReader/readAsDataURL

HTML

<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">

JavaScript:

function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();

reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);

if (file) {
reader.readAsDataURL(file);
}
}

try it on jsfiddle

If upload is needed it could be done AJAX.

Receiving Multipart Response on client side (ClosableHttpResponse)

I have finally got a workaround for it.

I will be using javax mail MimeMultipart.

Below is a code snipped for the solution:-

    ByteArrayDataSource datasource = new ByteArrayDataSource(in, "multipart/form-data");
MimeMultipart multipart = new MimeMultipart(datasource);

int count = multipart.getCount();
log.debug("count " + count);
for (int i = 0; i < count; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (bodyPart.isMimeType("text/plain")) {
log.info("text/plain " + bodyPart.getContentType());
processTextData(bodyPart.getContent());
} else if (bodyPart.isMimeType("application/octet-stream")) {
log.info("application/octet-stream " + bodyPart.getContentType());
processBinaryData(bodyPart.getInputStream()));
} else {
log.warn("default " + bodyPart.getContentType());
}
}

Please let me know if anybody else have any standard solution.

Weird issue when uploading file from JSP to Servlet

I figured it out. Had to remove the @MultipartConfig annotation, and implement the javax.servlet.Servlet interface, and use the Apache Commons FileUpload library.

Send a File to Servlet from JSP

file type of inputs are not simple attributes, they are sent in separate chunk of the request. Therefore you must have at least 2 parts in your HTTP request.

So, you must use Multipart Form Data processing to parse the file. There are a number of examples here, for example:

  • Convenient way to parse incoming multipart/form-data parameters in a Servlet
  • Java library for reading multipart/form-data http body containing multiple files

Most commonly the Apache Commons Fileupload http://commons.apache.org/fileupload is used for this.



Related Topics



Leave a reply



Submit