利用adodb.stream直接下载任何后缀的文件(防盗链)

原作:possible_Y,载自时代课堂

在浏览器的地址栏里直接输入一个doc或xls或jpg的文件的url路径,那么该文件会直接显示在浏览器里。而在很多时候我们希望能直接弹出下载提示框让用户下载,我们该怎么办呢?这里有两种方法:
1、设置你的服务器的iis,给doc等后缀名做映射
2、在向客户端发送时设置其contenttype

下面详细说明方法2

 1   
 2Response.Buffer = true   
 3Response.Clear 
 4
 5dim url   
 6Dim fso,fl,flsize   
 7dim Dname   
 8Dim objStream,ContentType,flName,isre,url1   
 9'*********************************************调用时传入的下载文件名   
10Dname=trim(request("n"))   
11'******************************************************************   
12If Dname<>"" Then   
13'******************************下载文件存放的服务端目录   
14url=server.MapPath("/")&"\"&Dname   
15'***************************************************   
16End If 
17
18Set fso=Server.CreateObject("Scripting.FileSystemObject")   
19Set fl=fso.getfile(url)   
20flsize=fl.size   
21flName=fl.name   
22Set fl=Nothing   
23Set fso=Nothing   
 1   
 2Set objStream = Server.CreateObject("ADODB.Stream")   
 3objStream.Open   
 4objStream.Type = 1   
 5objStream.LoadFromFile url 
 6
 7  
 8Select Case lcase(Right(flName, 4))   
 9Case ".asf"   
10ContentType = "video/x-ms-asf"   
11Case ".avi"   
12ContentType = "video/avi"   
13Case ".doc"   
14ContentType = "application/msword"   
15Case ".zip"   
16ContentType = "application/zip"   
17Case ".xls"   
18ContentType = "application/vnd.ms-excel"   
19Case ".gif"   
20ContentType = "image/gif"   
21Case ".jpg", "jpeg"   
22ContentType = "image/jpeg"   
23Case ".wav"   
24ContentType = "audio/wav"   
25Case ".mp3"   
26ContentType = "audio/mpeg3"   
27Case ".mpg", "mpeg"   
28ContentType = "video/mpeg"   
29Case ".rtf"   
30ContentType = "application/rtf"   
31Case ".htm", "html"   
32ContentType = "text/html"   
33Case ".txt"   
34ContentType = "text/plain"   
35Case Else   
36ContentType = "application/octet-stream"   
37End Select 
38
39Response.AddHeader "Content-Disposition", "attachment; filename=" & flName   
40Response.AddHeader "Content-Length", flsize 
41
42Response.Charset = "UTF-8"   
43Response.ContentType = ContentType 
44
45Response.BinaryWrite objStream.Read   
46Response.Flush   
47response.Clear()   
48objStream.Close   
49Set objStream = Nothing 

将下面的东西存成download.asp然后你就可以用

1<a herf=" http://www.knowsky.com/download.asp?n=file.doc">download!</a>

来下载同一目录下的file.doc了!

但是这里有个问题就是直接将file.doc路径写在url里是不安全的,所以解决方案应该是将file.doc的路径存到数据库里,同过查找数据库后得到路径

在这个程序的最前面如果加上一个判断:

if instr(Request.ServerVariables("HTTP_REFERER"),"http://你的域名")=0 then
Response.End
end if

就能够很好的防止别人的盗链了

Published At
Categories with Web编程
Tagged with
comments powered by Disqus