<%@ page import="java.io.*"%>
<%
String root=application.getRealPath("/");
String fileName=request.getParameter("fileName");
String filePath=request.getParameter("filePath");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment; filename=\"" +fileName+ "\"");
try{
java.io.OutputStream os = response.getOutputStream(); //不加此行将只能下载文本文件.下载jpg等就会出现打不开的现象.
java.io.FileInputStream fis = new java.io.FileInputStream(root+filePath);
byte[] b = new byte[1024];
int i = 0;
while ( (i = fis.read(b)) > 0 )
{
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
}
catch ( Exception e )
{
System.out.println ( "IOException." + e );
}
%>
java.io.FileInputStream fis = new java.io.FileInputStream(文件的真实路径);
也可以
<%
if (request.getParameter("fileUrl") != null)
{
String strFileUrl = request.getParameter("fileUrl");
//获取文件名(DealFile是自己写的一个处理文件的一个类)
DealFile dealFile = new DealFile(strFileUrl);
String filename = dealFile.getFileName();
response.setHeader("content-type","application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=\""+ filename+"\"");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
//从文件所在目录以流的方式读取文件
bis = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath(strFileUrl)));
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);
}
bos.flush();
}
catch(final IOException e)
{
System.out.println ( "IOException." + e );
}
finally
{
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return;
}
%>
posted on 2006-04-14 16:04
kelven 阅读(1453)
评论(0) 编辑 收藏 所属分类:
Java