我需要维护一个遗留软件。我们如何使用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
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.
我们需要添加:
<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);