在网上搜索到下载方法,总是有一些问题,浪费了一些时间.
1.response.reset();//清除首部的空白行
没加这个导致文件莫名其妙的多出0.01 KB之类,像音频文件直接导致不能使用
/**
* 网页文件下载
* @param response
* @param fileName 文件名
* @param contents
*/
public void downloadFile(HttpServletResponse response, String fileName, byte[] contents) {
if (fileName != null && contents.length !=0) {
response.reset();//清除首部的空白行
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
try {
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new ByteArrayInputStream(contents));
OutputStream os = response.getOutputStream();
int i ;
while ((i= bis.read(buffer)) != -1) {
os.write(buffer, 0, i);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
本文介绍了一种在网络文件下载过程中遇到的字节溢出问题解决方案,特别是针对文件大小出现莫名增加的情况,如0.01KB的误差,这在音频等文件中可能导致文件无法正常使用。通过在下载前使用response.reset()方法,可以有效清除HTTP响应头的空白行,避免此类问题的发生。
1752

被折叠的 条评论
为什么被折叠?



