gordon613
gordon613

Reputation: 2952

Java download corrupts .docx file by adding one character

My Web application runs Tomcat 8. A .docx file is correctly uploaded to the server, and is downloaded using the following java code contained within a jsp.

File f = new File (Monitor.getPropertyValue("myDir") + (request.getParameter("file")) );

  String filename=request.getParameter("original");
  response.setContentLength((int) f.length());
  response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessing‌​ml.document");

  response.setHeader ("Content-Disposition", "attachment; filename="+filename);
  InputStream in = new FileInputStream(f);
  ServletOutputStream outs = response.getOutputStream();


  int bit = 256;
  int i = 0;
  try {
  while ((bit) >= 0) {
  bit = in.read();
  outs.write(bit);
                     }
       } 
        catch (IOException ioe) {
                ioe.printStackTrace(System.out);
            }
   outs.flush();
   outs.close();
   in.close(); 

However when I try and open the downloaded file, it is corrupted and Word will not open it (without fixing it first)

When I compared the original file and the downloaded file then I noticed that the downloaded file has one extra character at the end - FF (hex)

If I remove this extra character with a Hex editor, then the file opens fine.

Why is this extra character being added?

Upvotes: 0

Views: 375

Answers (1)

Kayaman
Kayaman

Reputation: 73548

Your loop is wrong. After the last actual byte is written, bit still contains it, the loop is entered, in.read() reads -1 and writes it out, resulting in the extra 0xFF (i.e. -1) byte.

Change your loop to check what is read before writing it out as follows

while((bit = in.read()) != -1) {
    outs.write(bit);
}

Upvotes: 4

Related Questions