---
title: "JSP实现点击链接后下载文件(相当于右键另存)功能 "
author: "supercrsky"
date: "2009-07-01T16:03:50Z"
tags: ["JSP", "Servlet"]
categories: ["非技术"]
slug: "jsp"
draft: false
lastmod: "2009-07-01T16:19:16Z"
id: 418384
url: "https://supercrsky.iteye.com/blog/418384"
---

\[code="java"] /\** \*//\** * 实现文件另存功能 * * @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; } \[/code] 下载的action: \[code="java"] /\** \*//\** * 提供下载的方法 * @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; } \[/code] 页面链接调用: \[code="html"] [下载]($%7Bctx%7D/va/va%21down.do) \[/code]