用java IO流从数据库中读取文件下载,以前下载.doc,.xls都没有问题。但是发现.docx. xlsx下载时,出现了文件损坏的提示。如下图:

点确定后,又弹出
,我的代码如下:
String fileId = request.getParameter("fileId");
AttachFileVO attachFileVO = new AttachFileVO();
attachFileVO.setFileId(fileId);
AttachFileVO attachFile = applicationService.getAttachFile(attachFileVO);
String fileName = attachFile.getFileName();
String formatFileName = CommonUtil.encodingFileName(fileName);
if(attachFile!=null&&attachFile.getFileContent()!=null){
InputStream in = null;
OutputStream os = null;
try{
response.reset();
response.setContentType(attachFile.getFileType());
response.setHeader("Content-Disposition", "attachment;filename="+formatFileName);
in = new ByteArrayInputStream(attachFile.getFileContent());
byte[] buffer = new byte[1024];
os = response.getOutputStream();
while (in.read(buffer) > 0) {
os.write(buffer);
}
}catch(Exception ex){
throw ex;
}finally{
if(in!=null){
in.close();
}
if(os!=null){
os.close();
}
}
return null;
}------解决思路----------------------
把下面那段改成这样看看。
in = new ByteArrayInputStream(attachFile.getFileContent());
byte[] buffer = new byte[1024];
os = response.getOutputStream();
int len = 0;
while ((len = in.read(buffer)) > 0) {
os.write(buffer, 0, len);
}
------解决思路----------------------
尝试每次读取1024个字节,写入buffer数组,如果少于1024,就会返回实际读取的字节,os.write(buffer);可能多了