I am using Jersey (org.glassfish.jersey - version 2.22.2) - JAX-RS, Guice and implementing method for image upload:
@PUT
@Path("/image")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public ImageResponse putImage(@FormDataParam("image") InputStream uploadedInputStream) {
writeToFileWithOutputStream(uploadedInputStream);
return null;
}
private void writeToFileWithOutputStream(InputStream uploadedInputStream) {
try {
OutputStream out = new FileOutputStream(new File("xxx.jpg"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When I use write to file with method writeToFileWithOutputStream, I get file which does not open as image. It consists:
------WebKitFormBoundary5PVRYeRUBBAFA9yi
Content-Disposition: form-data; name="image"; filename="images.jpg"
Content-Type: image/jpeg
/** image symbols **/
------WebKitFormBoundary5PVRYeRUBBAFA9yi
Content-Disposition: form-data; name=""
------WebKitFormBoundary5PVRYeRUBBAFA9yi--
If I delete the top 4 lines manually, image opens properly.
I have tried to process them with BufferedReader/Writer but it is malformed because of Corrupted files uploaded on REST method call
Also tried to use ImageIO.read(inputStream) but it returns null.
What is the best way to process received image InputStream and save it as image (jpg, png or other format)?
1. code : When receiving an image with jersey, the stream received is not a String but a InputStream that you might read:
@OPTION
@Path("/image")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response putImag_opts(
@FormDataParam("image") InputStream stream,
@FormDataParam("image") FormDataContentDisposition fileDetail){
return Response.ok().build();
}
@PUT
@Path("/image")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response putImage(
@FormDataParam("image") InputStream stream,
@FormDataParam("image") FormDataContentDisposition fileDetail
) {
writeToFileWithOutputStream(stream);
//if ok...
return Response.ok().build();
}
informations:
- object stream
is the stream received,
- object fileDetail
contains files informations
2. dependencies : Please also check that you have the right dependency to upload image :
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.22.2</version>
</dependency>
3. register in you app class
Register content multipart in your App.class jersey
register(MultiPartFeature.class);