当前位置:主页 > 查看内容

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

发布时间:2021-07-10 00:00| 位朋友查看

简介:复制代码 代码如下: /** * 实现文件另存功能 * * @param text * 文件内容 * @param fileName * 文件名称 * @return */ protected String renderFile(String text, String fileName) throws IOException { response.addHeader("Content-Disposition", "attach……
复制代码 代码如下:

/**
* 实现文件另存功能
*
* @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>

本文转载自网络,原文链接:https://m.jb51.net/article/18938.htm
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐