ウェブサイトからファイルをダウンロードする方法-Java / Jsp
ここでは、ユーザーがWebサイトからファイルをダウンロードできるようにする方法を示す簡単なJavaの例を示します。 Struts、JSP、Spring、またはその他のJavaフレームワークを使用していても、ロジックは同じです。
1)まず、HttpServletResponse responseを設定して、システムが通常の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)完了
ここで、Strutsの例を示して、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("example");
writer.append(',');
writer.append("26");
writer.append(',');
writer.append("0123456789");
writer.append('\n');
return writer;
}