coke 2_0
coke 2_0

Reputation: 33

Error reading DOCX file generated from java server

In server side, I have a DOCX file that is correct. I have Java code to read the file from disk and flush it through a JSP.

When I download the file, Office says that the file contains errors. This is the code in my JSP:

    File dir = new File("c:\\file_test.docx");
    FileInputStream fin = new FileInputStream(dir);
    byte fileContent[] = new byte[(int)dir.length()];
    fin.read(fileContent);
    fin.close();
    response.setHeader("Content-Disposition", "attachment;filename=file_test.docx");
    response.setContentLength((int)dir.length());
    response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=utf-8");
    response.getOutputStream().write(fileContent);
    response.getOutputStream().flush();

I found that the downloaded file contains a blank line at the end. If I open the file with Notepad and delete the space, the file opens correctly.

My question is, in the JSP, how can I remove the white space at the end of the binary file? I tried to include all the bytes in the file except the last, but that doesn't work.

If I delete the line 6238, Office opens the file correctly. Edited with Notepad++

If I delete line 6238, Office opens the file correctly. Edited with Notepad++

I need your help!

Upvotes: 3

Views: 1245

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

The JSP outputs text when not being careful.

End with:

%>

without anything following, i.e. without line break

Or make it a servlet.

Upvotes: 3

Related Questions