Java Http Client to upload file over POST

Sending files over HTTP is supposed to take place using multipart/form-data encoding. Your servlet part is fine as it already uses Apache Commons FileUpload to parse a multipart/form-data request.

Your client part, however, is apparently not fine as you’re seemingly writing the file content raw to the request body. You need to ensure that your client sends a proper multipart/form-data request. How exactly to do it depends on the API you’re using to send the HTTP request. If it’s plain vanilla java.net.URLConnection, then you can find a concrete example somewhere near the bottom of this answer. If you’re using Apache HttpComponents Client for this, then here’s a concrete example, taken from their documentation:

String url = "https://example.com";
File file = new File("/example.ext");

try (CloseableHttpClient client = HttpClients.createDefault()) {
    HttpPost post = new HttpPost(url);
    HttpEntity entity = MultipartEntityBuilder.create().addPart("file", new FileBody(file)).build();
    post.setEntity(entity);

    try (CloseableHttpResponse response = client.execute(post)) {
        // ...
    }
}

Unrelated to the concrete problem, there’s a bug in your server side code:

File file = new File("\files\\"+item.getName());
item.write(file);

This will potentially overwrite any previously uploaded file with the same name. I’d suggest to use File#createTempFile() for this instead.

String name = FilenameUtils.getBaseName(item.getName());
String ext = FilenameUtils.getExtension(item.getName());
File file = File.createTempFile(name + "_", "." + ext, new File("/files"));
item.write(file);

Leave a Comment