ここでは、ユーザーがWebサイトからファイルをダウンロードできるようにするための簡単なJavaの例を示します。 Struts、JSP、Spring、その他のJavaフレームワークを使用していても、ロジックは同じです。
1)最初に、HttpServletResponseレスポンス** を設定して、システムが通常のhtmlページの代わりにアプリケーションファイルを返すようにブラウザに指示する必要があります
response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=downloadfilename.csv");
私たちはまた、上記の例の
attachment; filename =
にダウンロードファイル名を指定することができます。この例では、ユーザのダウンロードのためにcsvファイル名 “downloadfilename.csv”をエクスポートします。
{空} 2)ユーザーがウェブサイトからファイルをダウンロードできるようにする2つの方法があります
File file = new File("C:\\temp\\downloadfilename.csv"); FileInputStream fileIn = new FileInputStream(file); ServletOutputStream out = response.getOutputStream(); byte[]outputByte = new byte[4096];//copy binary contect to output stream while(fileIn.read(outputByte, 0, 4096) != -1) { out.write(outputByte, 0, 4096); } fileIn.close(); out.flush(); out.close();
-
データベースのデータや文字列をInputStreamに直接エクスポートしてユーザーのダウンロードを行う**
StringBuffer sb = new StringBuffer("whatever string you like"); InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8")); ServletOutputStream out = response.getOutputStream(); byte[]outputByte = new byte[4096];//copy binary contect to output stream while(in.read(outputByte, 0, 4096) != -1) { out.write(outputByte, 0, 4096); } in.close(); out.flush(); out.close();
{空} 3)完了
ここでは、InputStreamに直接データを書き込んで、それを “temp.cvs”として出力してユーザーにダウンロードさせる方法を示すためのストラットの例を示します。
public ActionForward export(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //tell browser program going to return an application file //instead of html page response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment;filename=temp.csv"); try { ServletOutputStream out = response.getOutputStream(); StringBuffer sb = generateCsvFileBuffer(); InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8")); byte[]outputByte = new byte[4096]; //copy binary contect to output stream while(in.read(outputByte, 0, 4096) != -1) { out.write(outputByte, 0, 4096); } in.close(); out.flush(); out.close(); } return null; } private static StringBuffer generateCsvFileBuffer() { StringBuffer writer = new StringBuffer(); writer.append("DisplayName"); writer.append(','); writer.append("Age"); writer.append(','); writer.append("HandPhone"); writer.append('\n'); writer.append("mkyong"); writer.append(','); writer.append("26"); writer.append(','); writer.append("0123456789"); writer.append('\n'); return writer; }
ここにリンクがあります://servlet/servlet-code-to-download-text-file-from-website-java/[サーブレットコードのファイルダウンロードの例]
リンク://タグ/ダウンロードファイル/[ダウンロードファイル]リンク://タグ/java/[java]
struts