简体   繁体   中英

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

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


Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
InputStream uploadedInputStream = filePart.getInputStream();

Try above code to parse request and extract file contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM