I've designed a multipart Jersey REST service as below to receive a multipart request (file uploads) and save the file in a disk location:
@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;
}
and my test client is:
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);
But I am not able to get the response.
It is working perfectly when I am using the HTML web page as the client to upload the files by calling the REST service but from the REST client it is not working.
Is there anything that has to be changed in the client?
The solution to this, if you don't have a file, but some String or so, is to do something like this:
When you say you're not able to get a response, what do you mean exactly ?
If you send a file, can you try with this ?
Also,
Shouldn't be named "file", but "filename" for example.
For debugging, I would advise you to listen on your server using Wireshark.