介绍
在使用io流下载服务器上的资源文件时,出现以下提示:但是选择“是”后文件可以正常打开
参考 代码如下:
[codesyntax lang="java"]
@RequestMapping(value = "downLoadInstruction")
public void downLoadInstruction(HttpServletRequest request,HttpServletResponse response) {
BufferedOutputStream out = null;
InputStream is = null;
try {
response.reset();
response.setCharacterEncoding("UTF-8");
String filename = "专家信息管理系统使用说明.docx";
response.setContentType("application/msword");
String templatePath = request.getSession().getServletContext().getRealPath("/template/instructionsForUse.docx");
//下载是否使用的火狐浏览器
String agent = request.getHeader("User-Agent");
boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
if(isMSIE){
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename, "UTF-8"));
}else{
response.setHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes("UTF-8"), "ISO-8859-1"));
}
out = new BufferedOutputStream(response.getOutputStream());
is = new BufferedInputStream(new FileInputStream(new File(templatePath)));
byte[] content = new byte[1024];
int len = 0;
while ((len = is.read(content)) > 0) {
out.write(content, 0, len);
}
//注释1
//out.write(content);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(is!=null){
is.close();
}
if(out!=null){
out.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
[/codesyntax]
代码中需要将注释1的地方注释掉,不然就会出现文件损坏,原因在于“尝试每次读取1024个字节,写入buffer数组,如果少于1024,就会返回实际读取的字节,os.write(buffer);可能多了“。
查看原文:http://surenpi.com/2017/01/03/java%e4%bd%bf%e7%94%a8io%e6%b5%81%e4%b8%8b%e8%bd%bd-docx-xlsx%e6%96%87%e4%bb%b6%ef%bc%8c%e5%87%ba%e7%8e%b0%e6%96%87%e4%bb%b6%e6%8d%9f%e5%9d%8f%e6%8f%90%e7%a4%ba/