Search code examples
javahttpfile-uploadapache-commons-httpclient

Apache HttpPost Multiple Files upload failes with server error - Missing initial multi part boundary


I try to upload multiple files, using Apache Http library.

   compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.5.6'

This is how I upload files.

String url = "url";
File f1 = new File("file1");
File f2 = new File("file2");
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type", "multipart/form-data");
request.addHeader("Authorization", "Basic abcd=");
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

FileBody fileBody1 = new FileBody(f1, ContentType.DEFAULT_TEXT);
FileBody fileBody2 = new FileBody(f2, ContentType.DEFAULT_TEXT);

multipartEntityBuilder.addPart("file_1_param", fileBody1);
multipartEntityBuilder.addPart("file_2_param", fileBody2);
HttpEntity httpEntity = multipartEntityBuilder.build();
request.setEntity(httpEntity);
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(request);

HttpEntity entity = response.getEntity();
if (entity == null) {
    return;
}

InputStream is = entity.getContent();
String textResponse = InputStreamUtils.readText(is);
System.out.println(textResponse);

It prints.

<pre>    Server Error</pre></p><h3>Caused by:</h3><pre>java.lang.RuntimeException: javax.servlet.ServletException: org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: Missing initial multi part boundary
at com.ca.devtest.acl.servlet.filters.RemoteAuthenticationFilter.doFilter(RemoteAuthenticationFilter.java:285)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)

It works if I upload only one file though!

Note, this is not a duplicate. These links show posts which refer the problem on the server side. This problem is with the client side.

Jetty throws "Missing content for multipart request" on multipart form request

500 Internal server error Android HttpPost file upload


Solution

  • I found out a resolution. I wanted to share it with other people, so you can 1) learn how to upload files and 2) pay attention to HTTP headers.

    When I append FileBody to MultipartEntityBuilder it automatically sets boundary. I simply removed this line from the code

     request.addHeader("Content-Type", "multipart/form-data"); //Remove it
    

    Example of a POST request with one or more files attached

    The Multipart Content-Type