javaを使ってファイルのダウンロードができません。
ネット上のサンプルを使い回しながら開発していますが、
setContentTypeの箇所でjava.lang.NullPointerExceptionが発生します。
原因は「response = null」にしてるからだと思われますが、
じゃあどうすればいいのか、見当がつかず困っております。
public String doDownload() throws Exception { --省略-- monthReportList = jdbcTemplate.queryForList("call ATT_REPORT_DEPT_REASON (?, ?)", month,getDeptId()); --省略- makeFile(monthReportList); //←ストアドで呼んだLISTをサーバ上のExcelファイルにアウトプット。ここまではできてる fileDownload(); //←Excelをダウンロード ★ここが上手く行かない★ --省略-- } public static void makeFile(List<?> dblist) throws Exception{ ※Excelファイル作成 --省略-- } public static void fileDownload() throws IOException { HttpServletResponse response = null; try{ // ダウンロードするファイルを取得 FileInputStream fi = new FileInputStream("C:\\workspace\\result.xlsx"); //↑makeFile()で作成されたExcelファイル byte[] b = new byte[fi.available()]; for (int i = 0; i < b.length; i++) b[i] = (byte)fi.read(); //ヘッダにattachmentを設定 response.setContentType("application/octet-stream; charset=utf-8"); "★★↑ココでjava.lang.NullPointerException発生★★" response.setHeader("Content-Disposition","attachment; filename=\"出力ファイル名\""); response.setContentLength(b.length); ServletOutputStream os = response.getOutputStream(); os.write(b); os.close(); fi.close(); }catch(Exception e){ e.printStackTrace(); } }
これらを参考にしました。当然、「response = null」なんて記述はなく、プログラム作ってる途中でresponseは初期化が必要とのメッセージが出たため、nullを入れてしまいました。
CodeZine
ひよっこSEのコツコツ備忘録
笑猫酒家(https://codezine.jp/article/detail/41)
回答2件
あなたの回答
tips
プレビュー