0
点赞
收藏
分享

微信扫一扫

java使用io流下载.docx. xlsx文件,出现文件损坏提示

介绍
在使用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);可能多了“。

举报

相关推荐

0 条评论