Using JAVA, I'm trying to force the browser to download files.
Here is the code I currently use:
response.reset();
response.resetBuffer();
response.setContentType(mimeType);
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
InputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
out.flush();
out.close();
in.close();
response.flushBuffer();
It works almost well, but when forcing the download of a docx
document (MS Office 2007+), the downloaded file is corrupted (at least, that's what MS Office tells me). If I try to open it directly on the server which stores them, that error doesn't appear, which means that the problem does interfere when downloading (and not when uploading).
According to IANA, the MIME type of such a file should be application/vnd.openxmlformats-officedocument.wordprocessingml.document
(1), but specifying that MIME type doesn't resolve the problem.
There are several tracks on the Web, but none of them worked for me. There seems to be a solution in ASP.NET
, but I didn't find the equivalent in JAVA
.
I also tried to use the MIME type application/vnd.ms-word
(2) as I saw there, but the downloaded file is still corrupted. Idem for the MIME type application/msword
(3) a guy suggested here, and for the generic MIME type application/octet-stream
(4) as put forward on this forum.
Then, for each of these four MIME types, I tried to change the name of the downloaded file from myfile.docx
to myfile.doc
(no x anymore), but the problem persists.
So, how to force the download of an uncorrupted-when-downloaded docx
file? Is my piece of code correct?