JSP 點擊鏈接后下載文件(相當(dāng)于右鍵另存)功能
更新時間:2009年07月01日 23:43:35 作者:
JSP 點擊鏈接后下載文件(相當(dāng)于右鍵另存)功能實現(xiàn)代碼。
復(fù)制代碼 代碼如下:
/**
* 實現(xiàn)文件另存功能
*
* @param text
* 文件內(nèi)容
* @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:
復(fù)制代碼 代碼如下:
/** *//**
* 提供下載的方法
* @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;
}
頁面鏈接調(diào)用:
復(fù)制代碼 代碼如下:
<a href="${ctx}/va/va!down.do" >下載</a>
相關(guān)文章
response.setContentType()的作用及MIME參數(shù)詳解
response.setContentType(MIME)的作用是使客戶端瀏覽器,區(qū)分不同種類的數(shù)據(jù),并根據(jù)不同的MIME調(diào)用瀏覽器內(nèi)不同的程序嵌入模塊來處理相應(yīng)的數(shù)據(jù),本文詳細(xì)介紹,需要了解的朋友可以參考下2012-12-12
JSP實現(xiàn)遠(yuǎn)程文件下載保存到服務(wù)器指定目錄中的方法
這篇文章主要介紹了JSP實現(xiàn)遠(yuǎn)程文件下載保存到服務(wù)器指定目錄中的方法,涉及JSP文件傳輸及目錄操作的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10

