Danny Dan
Danny Dan

Reputation: 1245

ServletOutputStream byte array to pdf corrupt pdf

I use tomcat 7.0.53, Struts 1.2.7, Spring 3.1.1. This is my code:

File file = new File("C:\\pdf\\" + report.getFileName());
FileOutputStream fos = new FileOutputStream(file);
fos.write(report.getData());
fos.close();

response.addHeader("Content-disposition", "application; filename="
                    + report.getFileName());
response.setContentType("application/pdf");
response.setContentLength(report.getData().length);

ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(report.getData());
outputStream.flush();

The file I get is right no problem there. But the file I get from response is corrupted. I tried to set encoding to response, tried to turn on spring CharacterEncodingFilter, tomcats SetCharacterEncodingFilter. Nothing helps. Where should I look at? p.s. this code is in Struts Action execute method

Upvotes: 1

Views: 1207

Answers (4)

webcom
webcom

Reputation: 1

I had the similar issue - corrupted binary pic. upon the download. Then while downloading TXT/XML files, I have noticed few blank lines at the beginning the text body.

Using the suggestion above on JSP, I removed all line breaks in my JSP page which manages the download. So all jsp and server tags follow in one single line:

<jsp:useBean.. ><%..response.  ;response.setStatus(HttpServletResponse.SC_RESET_CONTENT);return; %>

This removed extra blank lines in TXT/XML and solved binary corruption issue as well.

Olaf, thank you for the clue

Upvotes: -1

Danny Dan
Danny Dan

Reputation: 1245

I needed to return a null instead of an ActionForward so Struts knows the response was handled within the action.

Upvotes: 0

Olaf Kock
Olaf Kock

Reputation: 48057

you might want to save the result that you get from your webserver and compare it with the correct pdf. This way you'll see if there are some extra bytes at beginning or end, differences in encoding or whatever else is different.

Upvotes: 2

DavidC
DavidC

Reputation: 218

Remove response.setContentLength(report.getData().length); and try if it works, by doing this you also enable chunked data transmission.

Upvotes: 0

Related Questions