我设计了一个多部分 Jersey REST 服务,用于接收多部分请求(文件上传)并将文件保存在磁盘位置:
@POST
@Path("/Upload")
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(@FormDataParam("file") InputStream inputStream,
@FormDataParam("file") FormDataContentDisposition contentDisposition) {
System.out.println("Method Entry");
System.out.println(contentDisposition.getFileName());
String result = "not Success";
File file = null;
if (contentDisposition != null
&& contentDisposition.getFileName() != null
&& contentDisposition.getFileName().trim().length() > 0) {
try {
file = new File("xx"
+ contentDisposition.getFileName());
new File("yy").mkdirs();
file.createNewFile();
OutputStream outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.flush();
outputStream.close();
result = "success";
} catch (Exception e) {
System.out.println(e.toString());
}
}
System.out.println("Method Exit");
return result;
}
我的测试客户是:
Client client = Client.create();
WebResource resource = client
.resource("xyz");
String conString = "This is the content";
FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
formDataMultiPart.field("file", "Testing.txt");
FormDataBodyPart bodyPart = new FormDataBodyPart("file",
new ByteArrayInputStream(conString.getBytes()),
MediaType.APPLICATION_OCTET_STREAM_TYPE);
formDataMultiPart.bodyPart(bodyPart);
String reString = resource.type(MediaType.MULTIPART_FORM_DATA)
.accept(MediaType.TEXT_HTML)
.post(String.class, formDataMultiPart);
System.out.println(reString);
但我无法得到回应。
当我使用 HTML 网页作为客户端通过调用 REST 服务上传文件但从 REST 客户端它不工作时,它工作得很好。
客户端有什么需要改变的吗?