path_info. trim(). length()==0)
{
response.getWriter().println(“有以
下错误:[2000]未提供文件名”);
return;
}
String full_path = dir_info + path_info;
FileInputStream in = new FileInputStream(full_path);
response.setContentType(“bin”);
ServletOutputStream out = response.getOutputStream();
int b;
while ((b=in.read())!=-1)
{
out.write(b);
}
in.close();
}
catch(Exception e)
{
return;
}
}
可通过Http://localhost/servlet/Download/test. zip来下载c:\temp\test. zip文档。
第二种方法 间接路径法
间接路径法是指下载URL中不出现待下载文件名,下载URL主要用于实现权限控制,而在参数中提供文件名。这时,浏览器显示的下载名将不是实际下载文件名,而是用于权限控制的服务器程序的名称,必须将其名称改为原文件名。
这种方法主要利用HTTP头部响应协议(Http Header)来实现,其思路是:
1. 权限控制URL服务器程序验证用户的权限,若非法则拒绝服务。
2. 服务器程序从HTTP的参数变量中得到文件名,并通过事先的配置取得实际路径名。
3. 服务器程序利用HTTP响应头Content-disposition(详细说明可以参见rfc2183),设置下载文件名,如下所示:
Content-disposition: attachment; filename=下载文件名
4. 服务器程序将文件内容用流的方式读出,供合法用户下载。
这里的服务器程序可以是CGI、Servlet、JSP、ISAPI、ASP等。下面是用ASP实现的例子:
<%
Response.buffer = TRUE
dim strDir,strFullPath,strName
Dim vntStream
strDir=“c:\temp\”
if Session(“Download”)=“” then
’作为示例,简单权限判别
Response.write(“有以下错误:[1000]没
有权限”)
Response.end
end if
if Request(“filename”)=“” then
Response.write(“有以下错误:[2000]未
提供文件名”)
Response.end
end if
strName = Request(“filename”) strFullPath = strDir + strName Response.ContentType =“BIN”
’设置下载文件名
Response.addHeader“Content-disposition”, “attachment; filename=”& strName
Set oMyObject = Server.CreateObject(“MyObject. BinRead”)
’可自行开发的二进制读取对象
vntStream = oMyObject. readBinFile(strFullPath)
Response.BinaryWrite(vntStream)
Set oMyObject = Nothing Response.End
%>
可通过Http://localhost/Download.asp?filename=test.zip来下载c:\temp\test.zip文档。
此外,还可以利用操作系统中的功能来实现,但与系统关系太密切,不适于移植,除非该服务器是专门用来下载的,就不在此说明了。
关键词:下载信息内容时文件名称的指定