java - Extracting image from a request body results with a corrupted image (Spring MVC) -
i have problem has been bugging me whole week , have come dead end.
this scenario: have method in java spring controller handles http post request. post request contains picture. twist picture not sent multipart request, sent in requestbody (note answers saying change way of sending picture: have no access or possibility of doing this, have have).
so extract picture using input stream request. open output stream , write file, while reading input stream.
inputstream = request.getinputstream(); outputstream os = new fileoutputstream(new file("d:\\m\\" + request.getheader("content-location").tostring())); int x; while ((x = is.read()) != -1) { os.write(x); os.flush(); } os.close();
nothing fancy, plain old write read, byte byte.
the problem picture shown jpeg (as expected), can not open (i have tried multiple viewers , got same result):
name_of_pic.jpg decode error! not jpeg file: starts 0xbd 0xef
then said okay lets try way or output stream writing picture. of following code got me same result.
//alternative way1 datainputstream dis = new datainputstream(is); dataoutputstream dos = new dataoutputstream(new fileoutputstream(new file("d:\\m\\" + request.getheader("content-location").tostring()))); while(dis.available()>0){ int b = dis.read();//also tried readbyte, readunsignedbyte.. got 0kb file dos.write(b); dos.flush(); } dos.close(); //alternative way2 ioutils.copy(is, os); //alternative way3 int len = 0; byte[] buffer = new byte[8 * 1024]; while ((len = is.read(buffer, 0, buffer.length)) > 0) { (int = 0; < buffer.length; i++) { system.out.print(buffer[i]); } system.out.println(); os.write(buffer, 0, len); } os.flush(); os.close();
so looked @ requestbody in debugger , compared have in picture. there difference in values stored in requestbody , values stored in picture (after write on filesystem).
this picture shows few first values in requestbody: http://prntscr.com/7cuiw5
and how picture looks in hex value (using irfanview hex editor): http://prntscr.com/7culcn
clearly there difference write down.
the question go wrong? problem output stream reads int? or maybe conversion hex int/byte?
anyway stuck one. @ appreciated. sorry cant post pictures directly (not reputation).
when open image in notepad,you'll see code @ top , bottom.
-----------------------------119202331112770
content-disposition: form-data; name="file"; filename="..gif"
content-type: image/gif
this code has removed if wanna see images. these codes present in body of post method.
Comments
Post a Comment