サーバーに保管されているファイルをダウンロードする方法。
ダウンロード時の動作についてはレスポンスに設定する”Content-Disposition”の値次第になっていて、”attachment”であればダウンロードダイアログを表示するし、”inline”であればブラウザに直に表示する動きになる。
下のサンプルでは文字コードの設定とかもしてるけど、そこは環境依存なので注意。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
// ダウンロード対象ファイルの読み込み用オブジェクト FileInputStream fis = null; InputStreamReader isr = null; // ダウンロードファイルの書き出し用オブジェクト OutputStream os = null; OutputStreamWriter osw = null; try { // ダウンロード対象ファイルのFileオブジェクトを生成 File file = new File("ダウンロード対象ファイルのフルパス"); if (!file.exists() || !file.isFile()) { // ファイルが存在しない場合のエラー処理 } // レスポンスオブジェクトのヘッダー情報を設定 res.setContentType("application/octet-stream"); res.setHeader("Content-Disposition", "attachment; filename=" + new String("ダイアログに表示するファイル名".getBytes("Windows-31J"), "ISO-8859-1")); // ダウンロード対象ファイルの読み込み用オブジェクトを生成 fis = new FileInputStream(file); isr = new InputStreamReader(fis, "ISO-8859-1"); // ダウンロードファイルの書き出し用オブジェクトを生成 os = res.getOutputStream(); osw = new OutputStreamWriter(os, "ISO-8859-1"); // IOストリームを用いてファイルダウンロードを行う int i; while ((i = isr.read()) != -1) { osw.write(i); } } catch (FileNotFoundException e) { // 例外発生時処理 } catch (UnsupportedEncodingException e) { // 例外発生時処理 } catch (IOException e) { // 例外発生時処理 } finally { try { // 各オブジェクトを忘れずにクローズ if (osw != null) { osw.close(); } if (os != null) { os.close(); } if (isr != null) { isr.close(); } if (fis != null) { fis.close(); } } catch (IOException e) { // 例外発生時処理 } } |