<p>I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled.  I can open them but the image doesn't look like it should.  Here's my code:</p>

<p>Servlet</p>

<pre><code>protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    try {
      String customerPath = "\\leetest\\";

      // Check that we have a file upload request
      boolean isMultipart = ServletFileUpload.isMultipartContent(request);

      if (isMultipart) {
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
          FileItemStream item = iter.next();
          String name = item.getFieldName();
          if (item.isFormField()) {
            // Form field.  Ignore for now
          } else {
            BufferedInputStream stream = new BufferedInputStream(item
                .openStream());
            if (stream == null) {
              LOGGER
                  .error("Something went wrong with fetching the stream for field "
                      + name);
            }

            byte[] bytes = StreamUtils.getBytes(stream);
            FileManager.createFile(customerPath, item.getName(), bytes);

            stream.close();
          }
        }
      }
    } catch (Exception e) {
      throw new UploadException("An error occured during upload: "
          + e.getMessage());
    }
}
</code></pre>

<p>StreamUtils.getBytes(stream) looks like:</p>

<pre><code>public static byte[] getBytes(InputStream src, int buffsize)
      throws IOException {
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    byte[] buff = new byte[buffsize];
    while (true) {
      int nBytesRead = src.read(buff);
      if (nBytesRead &lt; 0) {
        break;
      }
      byteStream.write(buff);
    }

    byte[] result = byteStream.toByteArray();
    byteStream.close();

    return result;
}
</code></pre>

<p>And finally FileManager.createFile looks like:</p>

<pre><code>public static void createFile(String customerPath, String filename,
      byte[] fileData) throws IOException {
    customerPath = getFullPath(customerPath + filename);
    File newFile = new File(customerPath);
    if (!newFile.getParentFile().exists()) {
      newFile.getParentFile().mkdirs();
    }

    FileOutputStream outputStream = new FileOutputStream(newFile);
    outputStream.write(fileData);
    outputStream.close();
  }
</code></pre>

<p>Can anyone spot what I'm doing wrong?</p>

<p>Cheers,
Lee</p>

[{'answer_id': 41694, 'author': 'Nick Berardi', 'author_id': 17, 'author_profile': 'https://Stackoverflow.com/users/17', 'pm_score': 0, 'selected': False, 'text': "<p>Are you sure that the image isn't coming through garbled or that you aren't dropping some packets on the way in.  </p>\n"}, {'answer_id': 41748, 'author': 'Ben', 'author_id': 1417, 'author_profile': 'https://Stackoverflow.com/users/1417', 'pm_score': 0, 'selected': False, 'text': "<p>I don't know what difference it makes, but there seems to be a mismatch of method signatures.  The <code>getBytes()</code> method called in your <code>doPost()</code> method has only one argument:</p>\n\n<pre><code>byte[] bytes = StreamUtils.getBytes(stream);\n</code></pre>\n\n<p>while the method source you included has two arguments:</p>\n\n<pre><code>public static byte[] getBytes(InputStream src, int buffsize)\n</code></pre>\n\n<p>Hope that helps.</p>\n"}, {'answer_id': 41753, 'author': 'Craig', 'author_id': 1611, 'author_profile': 'https://Stackoverflow.com/users/1611', 'pm_score': 0, 'selected': False, 'text': '<p>Can you perform a checksum on your original file, and the uploaded file and see if there is any immediate differences?</p>\n\n<p>If there are then you can look at performing a diff, to determine the exact part(s) of the file that are missing changed.</p>\n\n<p>Things that pop to mind is beginning or end of stream, or endianness.</p>\n'}, {'answer_id': 42202, 'author': 'Stu Thompson', 'author_id': 2961, 'author_profile': 'https://Stackoverflow.com/users/2961', 'pm_score': 3, 'selected': True, 'text': "<p>One thing I don't like is here in this block from StreamUtils.getBytes():</p>\n\n<pre><code> 1 while (true) {\n 2   int nBytesRead = src.read(buff);\n 3   if (nBytesRead &lt; 0) {\n 4     break;\n 5   }\n 6   byteStream.write(buff);\n 7 }\n</code></pre>\n\n<p>At line 6, it writes the entire buffer, no matter how many bytes are read in.  I am not convinced this will always be the case.  It would be more correct  like this:</p>\n\n<pre><code> 1 while (true) {\n 2   int nBytesRead = src.read(buff);\n 3   if (nBytesRead &lt; 0) {\n 4     break;\n 5   } else {\n 6     byteStream.write(buff, 0, nBytesRead);\n 7   }\n 8 }\n</code></pre>\n\n<p>Note the 'else' on line 5, along with the two additional parameters (array index start position and length to copy) on line 6.</p>\n\n<p>I could imagine that for larger files, like images, the buffer returns before it is filled (maybe it is waiting for more).  That means you'd be unintentionally writing old data that was remaining in the tail end of the buffer.  This is almost certainly happening most of the time at EoF, assuming a buffer > 1 byte, but extra data at EoF is probably not the cause of your corruption...it is just not desirable.  </p>\n"}, {'answer_id': 42470, 'author': 'ScArcher2', 'author_id': 1310, 'author_profile': 'https://Stackoverflow.com/users/1310', 'pm_score': 1, 'selected': False, 'text': '<p>I\'d just use <a href="http://commons.apache.org/io/" rel="nofollow noreferrer">commons io</a> Then you could just do an IOUtils.copy(InputStream, OutputStream);</p>\n\n<p>It\'s got lots of other useful utility methods. </p>\n'}]
['https://Stackoverflow.com/questions/41686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1900/']