ASP程序中,有一些附件并不希望用已知程序直接打开,而是想点击时弹出下载提示。
我用了下面的代码:
<%
call downloadFile(Request("path"))function downloadFile(strFile)
strFilename = server.MapPath(strFile)
Response.Buffer = True
Response.Clear
Set s = Server.CreateObject(”ADODB.Stream”)
s.Open
s.Type = 1
on error resume next
Set fso = Server.CreateObject(”Scripting.FileSystemObject”)
if not fso.FileExists(strFilename) then
Response.Write(”<h1>Error:</h1>” & strFilename & ” does not exist<p>”)
Response.End
end if
Set f = fso.GetFile(strFilename)
intFilelength = f.size
s.LoadFromFile(strFilename)
if err then
Response.Write(”<h1>Error: </h1>” & err.Description & “<p>”)
Response.End
end if
Response.AddHeader “Content-Disposition”, “attachment; filename=” & f.name
Response.AddHeader “Content-Length”, intFilelength
Response.CharSet = “UTF-8″
Response.ContentType = “application/octet-stream”
Response.BinaryWrite s.Read
Response.Flush
s.Close
Set s = Nothing
End Function
%>
将上面的代码另存为down.asp放在要附件的目录下面(比如UpLoadFile/),然后引用:
<a href=”UpLoadFile/down.asp?path=<%=rs(”path”)%>”>点击下载</a>
UPDATE @ 2007.03.29:先道歉,上面的代码有一些问题,别人可以下载你的任何文件!fisker给出的补丁是在
function downloadFile(strFile)
后面加上
if left(strFile,1)="/" or
left(strFile,1)="\" or
left(strFile,2)=".." then response.end