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?

1
  • 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. Commented Aug 11, 2016 at 20:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Found this useful : int totalBytes = ByteStreams.toByteArray(this.imageStream).length; using Google guava as answered here: Convert InputStream to byte array in Java

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.