Search code examples
javafile-uploadjbossresteasy

How to upload a multipart file using org.jboss.resteasy.client.ClientRequest?


I need to maintain a legacy software. How do we use org.jboss.resteasy.client.ClientRequest to upload a file org.springframework.web.multipart.MultipartFile?

In short I would like to achieve: curl -X POST http://mydomain/upload?sender=mr_abc -F file=@${FILE} using ClientRequest. The ${FILE} can be any file as a string path example: /Users/mr_abc/mytarfile.tar.

Here what I have:

request = new ClientRequest("http://mydomain/upload");
request.header("Content-Type","multipart/form-data");
request.queryParameter("sender", "mr_abc");
request.queryParameter("file", new File("/Users/mr_abc/mytarfile.tar"));
ClientResponse<String> response = request.post(String.class);

Which resulted in error Required request part 'file' is not present


Solution

  • We would need to add:

    <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>resteasy-multipart-provider</artifactId>
                <version>3.0.19.Final</version>
                <scope>test</scope>
    </dependency>
    

    I tried earlier with version 2.3.5.Final, and that failed, so 3.0.19 seems to be a better version. and in the java code will need to use class MultiPartFormDataOutput

    File file = new File("/Users/mr_abc/mytarfile.tar");
    MultipartFormDataOutput upload = new MultipartFormDataOutput();
            upload.addFormData("file", targetStream, MediaType.MULTIPART_FORM_DATA_TYPE, "mytarfile.tar");
    
    request = new ClientRequest("http://mydomain/upload");
    
    request.queryParameter("sender", "mr_abc");
    request.body(MediaType.MULTIPART_FORM_DATA_TYPE, upload);
    ClientResponse<String> response = request.post(String.class);