下载 在action中
//读取数据库中保存的文件名称
String fileName = data.getFileName();
response.setContentType("application/msword");
response.setHeader("Content-disposition","attachment; filename="+fileName);
ServletContext context = servlet.getServletContext();
String filePath = context.getRealPath("wenjian/");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String path = filePath + "\\" +fileName;
try {
bis = new BufferedInputStream(new FileInputStream(path));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
}
} catch(final IOException e) {
System.out.println ( "出现IOException." + e );
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
本文介绍了一种在Java Web应用中实现文件下载的方法。通过读取数据库中的文件名,并设置HTTP响应头来触发浏览器下载指定文件。文章详细展示了如何使用BufferedInputStream和BufferedOutputStream进行文件读写操作。
1518

被折叠的 条评论
为什么被折叠?



