VwpFAQhyperlinkdownloadJa
ハイパーリンク: ファイルをダウンロードするハイパーリンクを設定する方法を教えてください。
ページを作成して、ページにたくさんのリンクを配置すると仮定します。 ユーザーがリンクをクリックすると、ブラウザの標準の保存用ダイアログを開くことを考えます。 ブラウザが MIME タイプを処理する方法を知っている場合もダイアログを開きます。
ヒントを以下に示します。Web アプリケーションの resources ディレクトリにある Sunset.jpg という名前のファイルをユーザーにダウンロードさせる場合の方法です。
- プロジェクトを作成し、ページに「ハイパーリンク」コンポーネントを追加します。
(ハイパーリンクの「text」プロパティーにアップロードするファイル名を設定します。例: Sunset.jpg)
- 別のページを「download」という名前で作成します。
- ナビゲーションエディタに移動し、ハイパーリンクから download ページへのリンクを作成し、リンク名を「download」に設定します。
- SessionBean1 に「downloadFile」という名前のプロパティを追加します。
- ハイパーリンクをダブルクリックして、Java ページで次のコードを追加します。
(戻り値が returns "download" になっていること確認します。)
public String hyperlink1_action() {
this.getSessionBean1().setDownloadFile((String)hyperlink1.getText());
return "download";
}
- download ページの init() メソッドに、次のコードを追加します。
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();
}
- プロジェクトを実行し、リンク Sunset.jpg をクリックすると、ブラウザは「名前を付けて保存」ダイアログを表示します。
- 日本語訳 : Yuko Ohsumi
- 英文 (翻訳したバージョン: 2)
- 日本語 NetBeans Visual Web Pack ユーザー FAQ へ戻る
