怎么实现一个下载页面,使点击页面上的链接时不是直接打开文件(txt,doc等等),而是下载。用jsp。用到struts的话,用struts2.1。 2.0也可以.
Struts 2中实现文件下载(修正中文问题)
http://www.blogjava.net/beansoft/archive/2008/03/03/183468.html
http://download.csdn.net/source/239425
http://www.blueidea.com/tech/program/2008/5258.asp
一个是上传下载的源代码 一个是讲解+代码 去看看吧 呵呵
创建一个下载页,把需要下载的文件路径和名称参数传入该页面,你也可以把这些代码放到action中。
[code="Jsp"]
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="java.io.*"%>
<%
String filename = request.getParameter("filename");//"1a.txt";
String filepath = request.getParameter("filepath");//"d:\";
try {
if (filename == null || filepath == null || "".equals(filename) || "".equals(filepath)) {
out.write("找不到要下载的文件!");
} else {
String fullpath = filepath + filename;
File file = new File(fullpath);
if (file == null || !file.exists()) {
out.write("找不到要下载的文件!");
} else {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename = " + filename);
BufferedInputStream input = new BufferedInputStream(new FileInputStream(fullpath));
byte buffBytes[] = new byte[1024];
int allLength = 0;
System.out.println("下载文件路径:" + fullpath);
System.out.println("开始下载");
OutputStream os = response.getOutputStream();
System.out.println("获得流之前");
int read = 0;
while ((read = input.read(buffBytes)) != -1) {
allLength += read;
os.write(buffBytes, 0, read);
}
System.out.println("获得流之后:" + allLength);
os.flush();
os.close();
input.close();
System.out.println("正常关闭文件流");
}
}
} catch (Exception e) {
e.printStackTrace();
out.write("程序出错!");
}
%>
[/code]