如何使用org.jboss.resteasy.client.ClientRequest上传多部分文件?

时间:2019-03-18 13:15:48

标签: java file-upload jboss resteasy

我需要维护旧版软件。我们如何使用org.jboss.resteasy.client.ClientRequest上传文件org.springframework.web.multipart.MultipartFile

简而言之,我想实现: curl -X POST http://mydomain/upload?sender=mr_abc -F file=@${FILE}使用ClientRequest${FILE}可以是任何文件,例如字符串路径:/Users/mr_abc/mytarfile.tar

这是我拥有的:

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

导致错误的原因 Required request part 'file' is not present

2 个答案:

答案 0 :(得分:0)

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.

答案 1 :(得分:0)

我们需要添加:

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

我之前尝试使用2.3.5.Final版本,但失败了,因此3.0.19似乎是更好的版本。 并且在Java代码中将需要使用类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);