public static void downloadFile(String filePath, javax.servlet.http.HttpServletResponse response) {
String fileName = ""; //文件名,输出到用户的下载对话框
//从文件完整路径中提取文件名,并进行编码转换,防止不能正确显示中文名
try {
if (filePath.lastIndexOf("/") > 0) {
fileName = new String(filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length()).getBytes(
"GB2312"), "ISO8859_1");
} else if (filePath.lastIndexOf("\\") > 0) {
fileName = new String(filePath.substring(filePath.lastIndexOf("\\") + 1, filePath.length()).getBytes(
"GB2312"), "ISO8859_1");
}
} catch (Exception e) {
}
//打开指定文件的流信息
FileInputStream fs = null;
try {
fs = new FileInputStream(new File(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
//设置响应头和保存文件名
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
//写出流信息
int b = 0;
try {
PrintWriter out = response.getWriter();
while ((b = fs.read()) != -1) {
out.write(b);
}
fs.close();
out.close();
System.out.println("文件下载完毕.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("下载文件失败!");
}
}
String fileName = ""; //文件名,输出到用户的下载对话框
//从文件完整路径中提取文件名,并进行编码转换,防止不能正确显示中文名
try {
if (filePath.lastIndexOf("/") > 0) {
fileName = new String(filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length()).getBytes(
"GB2312"), "ISO8859_1");
} else if (filePath.lastIndexOf("\\") > 0) {
fileName = new String(filePath.substring(filePath.lastIndexOf("\\") + 1, filePath.length()).getBytes(
"GB2312"), "ISO8859_1");
}
} catch (Exception e) {
}
//打开指定文件的流信息
FileInputStream fs = null;
try {
fs = new FileInputStream(new File(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
//设置响应头和保存文件名
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
//写出流信息
int b = 0;
try {
PrintWriter out = response.getWriter();
while ((b = fs.read()) != -1) {
out.write(b);
}
fs.close();
out.close();
System.out.println("文件下载完毕.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("下载文件失败!");
}
}