程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> JSP 點擊鏈接後下載文件(相當於右鍵另存)功能

JSP 點擊鏈接後下載文件(相當於右鍵另存)功能

編輯:關於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>
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved