-ファイルダウンロードのTips
ファイルダウンロードのサービスをTapestryで書いたのですが、できあがってから悩んだのが、ダウンロードするファイル名です。ServiceLinkのparametersサービスパラメータでオブジェクトをシリアライズしたものをリンクで飛ばして、サービス側でそのオブジェクトをチェックして後に動的に作成したCSVをダウンロードさせるものだったので、URLは以下のような感じになるのです。
http://localhost:8080/app?service=csv&sp=l1083576642915&sp=JaOih6p6IaK76l4U(後略)
このURLでアクセスしてファイルをダウンロードすると、保存を行うクライアント側のダイアログでファイル名がきちんと出ないのです。でも、以下のようにするのは作り上できないのです。
ということで、いろいろ調べているうちにJGrueでみつけました。えらいぞjGrue!ポイントは以下のコードの赤い部分。ヘッダに「Content-Disposition: attachment; filename=...」ですか。なるほど。
public void service(IEngineServiceView serviceView, IRequestCycle cycle, ResponseOutputStream out) throws ServletException, IOException { try { Object[] params = getParameters(cycle); long oneshotKey = ((Long)params[0]).longValue(); Job job = (Job)params[1]; cycle.getRequestContext().getResponse().setHeader( "Content-Disposition", "attachment; filename=\"" + job.getJobID() + ".csv\""); PrintWriter writer = new PrintWriter(out); operation.dumpCSV(writer, oneshotKey, job); } catch (Exception e) { log(ERROR_CSV_SERVICE, e); throw new ServletException(e); } }
IEngineServiceについては、[tapestry-article]でそのうちまとめます。