response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
String filePath = request.getParameter("filePath");
filePath = Tools.encodeStr(filePath, "iso-8859-1", "utf-8");
filePath = request.getSession().getServletContext().getRealPath(filePath);
String fileName = request.getParameter("fileName");
fileName = Tools.encodeStr(fileName, "iso-8859-1", "utf-8");
try {
long fileLength = new File(filePath).length();
//定义下载类型(也就是保存文件的后缀名,根据浏览器不同,规范严格的会把后缀改成设置的后缀)
//定义后缀为.exe的文件
response.setContentType("application/x-msdownload;");
//定义后缀为Java的文件(设置为Java后缀,opera就不会出现更改后缀的问题)
response.setContentType("application/java");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(filePath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}