Java プログラムメモ


トップ

Servlet でファイルをダウンロードする

HttpServletResponse から OutputStream を取得して、 そこにダウンロードしたいデータを流し込めばダウンロード可能です。
ContentType は適宜設定してください。 また、ダウンロード後のファイル名の設定方法は『Servlet でダウンロードするファイル名を設定する』 を参照してください。

ソース記述例

private void download(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream out = null; InputStream in = null; try { response.setContentType("application/octet-stream"); response.setHeader( "Content-Disposition", "filename=\"ファイル名\""); in = new FileInputStream("物理ファイル名"); out = response.getOutputStream(); byte[] buff = new byte[1024]; int len = 0; while ((len = in.read(buff, 0, buff.length)) != -1) { out.write(buff, 0, len); } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }


プログラムメモ アフリカ雑貨や農作物のセレクトショップ - はろの屋 マゴソスクール クラウドファンディング
SEO [PR] 爆速!無料ブログ 無料ホームページ開設 無料ライブ放送