在網上搜索到下載方法,總是有一些問題,浪費了一些時間.
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();
writeLog("downloadFile_response_set:"+e);
}
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();
}
}
}
}
}