首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

JSP 實作點擊連結下載檔案功能

     編輯:關於JSP

透過設定 HTTP 回應標頭 Content-Disposition: attachment,強制瀏覽器彈出「另存新檔」對話框,而非直接開啟檔案。

核心方法:renderFile

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 範例

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="down.action">下載</a>

關鍵點說明

  • Content-Disposition: attachment:指示瀏覽器下載而非顯示。
  • application/octet-stream:通用二進位流 MIME 類型,適用任意檔案。
  • filename 參數:建議經 URLEncoder.encode 處理中文檔名,避免亂碼。
  • 輸出流寫入後需 flushBuffer() 並 close() 確保資料完整送達。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved