【JSP】ファイルダウンロード機能の実装。

以前に、PHPで実装したものJSP版、といったところです。


たとえば、
「/data/www/secure/enqLog/」
に置かれているtsvファイルをダウンロードしたい場合、

response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment; filename=/data/www/secure/enqLog/choo.tsv");

ちなみに、responseはHttpServletResponseのオブジェクトですが、サーブレットコンテナで
デフォルトで定義されるオブジェクトなので、特に宣言することなく使えます(・∀・)


上で書いたプログラムを実行してみたところ、指定したTSVファイルではなく
JSPページ全体のソースが表示されてしまいました…(´・ω・`)
なので、以下が改良版のソースです。

<%@ page import="java.io.*, java.util.*" contentType="text/html; charset=Shift-JIS" %>
<%

//フォーム送信値の文字コード指定
request.setCharacterEncoding("Shift-JIS");

//フォーム送信データの受け取り
String type = request.getParameter("type");


if(type != null){
  String papapath = "../../../secure/enqLog/" + type + "/enqLog.tsv";
  File moto = new File(application.getRealPath(papapath));
  BufferedInputStream in = null;
  BufferedOutputStream outout = null;
  try{
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition","attachment; filename=\"" + moto.getName() + "\""); 
    in = new BufferedInputStream(new FileInputStream(moto));
    outout = new BufferedOutputStream(response.getOutputStream());


    byte buf[]=new byte[1024];
    int nagasa;
    while*1!=-1){
        outout.write(buf,0,nagasa);
    }
  }catch(Exception e){
    // 例外処理
  }finally{
    if (in != null) {
        in.close();
    }
    if (outout != null) {
        outout.flush();
        outout.close();
    }
  }


}else{
  return;
}


%>

*1: nagasa = in.read(buf