我的Web应用程序运行Tomcat 8。
.docx文件已正确上载到服务器,并使用jsp中包含的以下Java代码下载。
File f = new File (Monitor.getPropertyValue("myDir") + (request.getParameter("file")) );
String filename=request.getParameter("original");
response.setContentLength((int) f.length());
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setHeader ("Content-Disposition", "attachment; filename="+filename);
InputStream in = new FileInputStream(f);
ServletOutputStream outs = response.getOutputStream();
int bit = 256;
int i = 0;
try {
while ((bit) >= 0) {
bit = in.read();
outs.write(bit);
}
}
catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
outs.flush();
outs.close();
in.close();
但是,当我尝试打开下载的文件时,它已损坏并且Word无法打开它(未先修复)
当我比较原始文件和下载的文件时,我注意到下载的文件末尾有一个额外的字符-FF(十六进制)
如果我使用十六进制编辑器删除了此多余的字符,则文件可以正常打开。
为什么要添加这个额外的字符?
最佳答案
您的循环是错误的。写入最后一个实际字节后,bit
仍包含该字节,进入循环,in.read()
读取-1
并将其写出,从而产生额外的0xFF
(即-1
)字节。
更改循环以检查要读取的内容,然后将其写出,如下所示
while((bit = in.read()) != -1) {
outs.write(bit);
}