ページを作成して、ページにたくさんのリンクを配置すると仮定します。 ユーザーがリンクをクリックすると、ブラウザの標準の保存用ダイアログを開くことを考えます。 ブラウザが MIME タイプを処理する方法を知っている場合もダイアログを開きます。
ヒントを以下に示します。Web アプリケーションの resources ディレクトリにある Sunset.jpg という名前のファイルをユーザーにダウンロードさせる場合の方法です。
public String hyperlink1_action() {
this.getSessionBean1().setDownloadFile((String)hyperlink1.getText());
return "download";
}
ServletContext context = (ServletContext) getExternalContext().getContext();
HttpServletResponse response = (HttpServletResponse) getExternalContext().getResponse();
response.setContentType("application/force-download");
String downloadFile = this.getSessionBean1().getDownloadFile();
response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadFile + "\"");
byte[] buf = new byte[1024];
try{
String realPath = context.getRealPath("/resources/" + downloadFile);
File file = new File(realPath);
long length = file.length();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
ServletOutputStream out = response.getOutputStream();
response.setContentLength((int)length);
while ((in != null) && ((length = in.read(buf)) != -1)) {
out.write(buf, 0, (int)length);
}
in.close();
out.close();
}catch (Exception exc){
exc.printStackTrace();
}