Java言語でファイルをダウンロードサンプルコード

サンプルコード:

Dao dao = new Dao();
UploadFiles files = dao.querykById(id);
String uploadpath = “D:/startnews24/csg";
String path = uploadpath + files.getPath();
InputStream bis = null;
OutputStream bos = null;
try {
File fileInstance = new File(path);
if (!fileInstance.exists()) {
System.out.println(“———ファイルが存在しないです、管理者に連絡してください————-“);
} else {
HttpServletResponse response = (HttpServletResponse) ActionContext
.getContext().get(ServletActionContext.HTTP_RESPONSE);
bis = new BufferedInputStream(new FileInputStream(fileInstance));
bos = new BufferedOutputStream(response.getOutputStream());

response.setContentType(“application/octet-stream;charset=UTF-8");
response.setHeader(“Content-Disposition","attachment;filename="+ URLEncoder.encode(files.getUploadRealName(),"UTF-8″));
byte[] buff = new byte[1024];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
// buffのデータをクライアントのメモリに書き込む
bos.write(buff, 0, bytesRead);
}
bos.close();
bis.close();
}
} catch (IOException e) {
System.out.println(“ダウンロードを失敗した");
} finally {
bos.close();
bis.close();
}
return null;
}

Source

Posted by arkgame