Search code examples
javaresteasymultipart

How to send list of files by RESTEasy java


How can we send list of files by RESTEasy java client? Spring REST is:

@PostMapping()
public ResponseEntity<?> send(@RequestPart(value = "message") String message, @RequestPart(value = "attachment", required = false) List<MultipartFile> attachments)

In Postman it is made by specifying multiple files in form-data with one key "attachment", but MultipartFormDataOutput has Map inside, so it remembers only the last added file.


Solution

  • I have resolved this problem with using org.apache.http.entity.mime.MultipartEntityBuilder:

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("message", messageStr, ContentType.TEXT_PLAIN.withCharset(UTF_8));
    for (File file: files) {
        builder.addBinaryBody(
                "attachment",
                new FileInputStream(file),
                ContentType.APPLICATION_OCTET_STREAM,
                file.getName()
        );
    }
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = new HttpPost(url);
    uploadFile.setEntity(builder.build());
    CloseableHttpResponse response = httpClient.execute(uploadFile);