当前位置: 首页 > 图文教程 > 网络编程 > JSP > JSP 点击链接后下载文件(相当于右键另存)功能

JSP
Java布局管理器使用方法
JDK 1.5之Generics
掌握JDK1.5枚举类型
XML到Java代码的数据绑定之对象
基于JNDI的应用程序开发
Java语言中链表和双向链表
Java语言的接口与类型安全
Java数据库存取技术
Java中对HashMap的深度分析
Java线程模型缺陷
Java新手入门的30个基本概念
JBuilder2005单元测试体验之测试配置
JBuilder2005单元测试之创建测试固件
JBuilder2005单元测试之捆绑多个用例
JBuilder2005单元测试之业务类介绍
JBuilder2005单元测试之JUnit框架
JBuilder 2005单元测试之慨述
轻松玩转Java配置的Classpath
Eclipse中自动重构实现探索
为Java应用程序添加退出事件响应

JSP 点击链接后下载文件(相当于右键另存)功能


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 72 ::
收藏到网摘: n/a

JSP 点击链接后下载文件(相当于右键另存)功能实现代码。
复制代码 代码如下:

/**
* 实现文件另存功能
*
* @param text
* 文件内容
* @param fileName
* 文件名称
* @return
*/
protected String renderFile(String text, String fileName)
throws IOException
{
response.addHeader("Content-Disposition", "attachment; filename="
+ fileName);
response.setContentType("application/octet-stream");
response.setCharacterEncoding("GB2312");
response.getWriter().write(text);
response.flushBuffer();
response.getWriter().close();
return null;
}

下载的action:
复制代码 代码如下:

/** *//**
* 提供下载的方法
* @return
*/
public String down()
{
String dir = getFullPath() + "/upload/file/";
try
{
if (!FileUtils.exists(dir))
{
new File(dir).mkdirs();
}
Random r = new Random(System.currentTimeMillis());
Integer randomInt = r.nextInt();
this.renderFile("test content:" + randomInt,randomInt + ".txt");
}
catch (IOException e)
{
e.printStackTrace();
this.renderText(e.getMessage());
}
return null;
}

页面链接调用:
复制代码 代码如下:

<a href="${ctx}/va/va!down.do" >下载</a>