Forcing the browser to download a docx file in JAVA generates a corrupted document

房东的猫 提交于 2019-12-31 04:40:07

问题


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?


回答1:


I tried by chance to add more headers, and in fact, the Content-Length header resolved the problem...

So finally, I just add this line to make it work:

response.setContentLength((int) file.length());


来源:https://stackoverflow.com/questions/10431317/forcing-the-browser-to-download-a-docx-file-in-java-generates-a-corrupted-docume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!