0

I have a strange issue:

My dropwizard API processes the uploaded file and saves it as a JPEG image

the uploaded file is read as an InputStream.

FormDataBodyPart fileBody is read using @FormDataParam("file")

InputStream imageStream = fileBody.getValueAs(InputStream.class);
final int maxSize = 102400;
final byte[] bytes = new byte[maxSize + 1];
int totalBytes = this.imageStream.read(bytes);
System.out.println("totalBytes:"+totalBytes);

the totalBytes value returned is never greater than 8181 irrespective of the original size of the uploaded file. I tried with 800KB and 1.3MB files

the HttpServletRequest.getContentLength() shows the correct number of bytes as uploaded

what am I missing here?

Manohar
  • 35
  • 8
  • I just like to note that magic number `8181` has some possible explanation: `8181*8=65 448 ~ 65 536 = 2^16` -> `16 bits = 2 bytes`. I might be wrong. – ZbyszekKr Aug 11 '16 at 20:35

1 Answers1

0

InputStream.read(byte[])

doesn't guarantee to read the full content. From the javadoc:

Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

It seems that only 8181 bytes are available on the first call. You need to continue reading until the method returns -1 and combine all the bytes read.

Guenther
  • 2,035
  • 2
  • 15
  • 20
  • Found this useful : `int totalBytes = ByteStreams.toByteArray(this.imageStream).length;` using Google guava as answered here: [Convert InputStream to byte array in Java](http://stackoverflow.com/a/23455220/3175357) – Manohar Aug 11 '16 at 20:52