Apache HttpPost多个文件上传失败,并显示服务器错误-缺少初始多部分边界

时间:2018-09-04 09:52:45

标签: java http file-upload apache-commons-httpclient

我尝试使用Apache Http库上传多个文件。

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

这就是我上传文件的方式。

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);

它打印。

<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)

即使我仅上传一个文件也可以!

注意,这不是重复项。这些链接显示了在服务器端提及问题的帖子。问题出在客户端。

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

500 Internal server error Android HttpPost file upload

2 个答案:

答案 0 :(得分:2)

我找到了解决方案。我想与其他人共享它,因此您可以1)学习如何上传文件,2)注意HTTP标头。

当我将FileBody附加到MultipartEntityBuilder时,它会自动设置边界。我只是从代码

中删除了这一行
 request.addHeader("Content-Type", "multipart/form-data"); //Remove it

Example of a POST request with one or more files attached

The Multipart Content-Type

答案 1 :(得分:0)

从标题中完全删除ItemEntity选项以使其起作用。

示例

content-type