I'm using Struts for a file upload/download routine. All works well except that if I
download (using IE 6.x), get a message box asking if I want to save or open the file,
I get different results. If I save the file, then open it, it's fine. If I open it
directly (using a .txt file as an example), I get an error like "Cannot file the file
... Would you like to create a new one?" which I say 'yes' to, but the the file opens
and it's blank.
The example I cite uses Notepad, but the behavior is the same whether I download an
Excel file, a Word, a PDF -- Opening directly from the browser results in a blank
file. Saving and opening works fine. I gotta believe I'm doing something
not-quite-right in my Action. My code follows. Does anybody see a flaw?
Dave
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest request,
HttpServletResponse response) throws
FpdException, NumberFormatException, SQLException, IOException {
// get the document
int documentID = getDocumentId(request);
Document document = new Document(documentID);
// load it from the database
Connection cn = getConnection(request);
document.sqlLoad(cn);
cn.close();
// get contents into a convenient variable
byte[] bytes = document.getContents();
if (bytes.length == 0) {
throw new FpdException("File is blank; it has zero bytes");
}
String filename = createFilename(document);
// set the response headers
response.setContentType("application/download");
response.setContentLength(bytes.length);
response.setHeader("Content-Disposition",
"attachment; filename=\"" + filename + "\";");
BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(
bytes));
ServletOutputStream out = response.getOutputStream();
byte[] data = new byte[1024];
while (in.read(data) > -1) {
out.write(data);
}
in.close();
response.flushBuffer();
// return nothing so it stops there
return null;
}
========================== END ===============================