1.jsp页面用超链接请求至Action。示例:
<a href="#" οnclick="javascript:document.location.href='clientManagerAction.do?actionType=downloadExcel';">导入文件模板下载</a>
2.在Action中完成文件下载操作(并解决中文文件名乱码问题)
示例:
String fileType = request.getParameter("fileType");
String filePath = request.getParameter("filePath");
String fileName = null;
try {
fileName = new String(request.getParameter("fileName")
.getBytes("iso8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
// 创建file对象
String myFilePath = uploadFilePath + filePath + fileName;
File file = new File(myFilePath);
// 写明要下载的文件的大小
response.setContentLength((int) file.length());
try {
if (request.getHeader("User-Agent").toLowerCase().indexOf(
"firefox") > 0) {
fileName = new String(fileName.getBytes("UTF-8"),
"ISO8859-1");
} // firefox浏览器
else if (request.getHeader("User-Agent").toUpperCase().indexOf(
"MSIE") > 0) {
fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=\""
+ fileName + "\"");
response.setHeader("Connection", "close");
// 读出文件到i/o流
FileInputStream fis;
try {
fis = new FileInputStream(file);
BufferedInputStream buff = new BufferedInputStream(fis);
byte[] b = new byte[1024];// 相当于我们的缓存
long k = 0;// 该值用于计算当前实际下载了多少字节
// 从response对象中得到输出流,准备下载
OutputStream myout = response.getOutputStream();
// 开始循环下载
while (k < file.length()) {
int j = buff.read(b, 0, 1024);
k += j;
// 将b中的数据写到客户端的内存
myout.write(b, 0, j);
}
// 将写入到客户端的内存的数据,刷新到磁盘
myout.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
return forward;