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