当前位置: 移动技术网 > IT编程>开发语言>Asp > 使用asp下的adodb.stream 下载文件而不是打开

使用asp下的adodb.stream 下载文件而不是打开

2017年12月12日  | 移动技术网IT编程  | 我要评论

在浏览器的地址栏里直接输入一个doc或xls或jpg的文件的url路径,那么该文件会直接显示在浏览器里。而在很多时候我们希望能直接弹出下载提示框让用户下载,我们该怎么办呢?这里有两种方法: 

1、设置你的服务器的iis,给doc等后缀名做映射。

2、在向客户端发送时设置其contenttype。 

下面详细说明方法2 

程序代码: 

<% 
response.buffer = true 
response.clear 

dim url 
dim fso,fl,flsize 
dim dname 
dim objstream,contenttype,flname,isre,url1 
'*********************************************调用时传入的下载文件名 
dname=trim(request("n")) 
'****************************************************************** 
if dname<>"" then 
'******************************下载文件存放的服务端目录 
 url=server.mappath("/")&"\"&dname 
'*************************************************** 
end if 

set fso=server.createobject("scripting.filesystemobject") 
 set fl=fso.getfile(url) 
 flsize=fl.size 
 flname=fl.name 
 set fl=nothing 
 set fso=nothing 
%> 
<% 
 set objstream = server.createobject("adodb.stream") 
 objstream.open 
 objstream.type = 1 
 objstream.loadfromfile url 


 select case lcase(right(flname, 4)) 
 case ".asf" 
  contenttype = "video/x-ms-asf" 
 case ".avi" 
  contenttype = "video/avi" 
 case ".doc" 
  contenttype = "application/msword" 
 case ".zip" 
  contenttype = "application/zip" 
 case ".xls" 
  contenttype = "application/vnd.ms-excel" 
 case ".gif" 
  contenttype = "image/gif" 
 case ".jpg", "jpeg" 
  contenttype = "image/jpeg" 
 case ".wav" 
  contenttype = "audio/wav" 
 case ".mp3" 
  contenttype = "audio/mpeg3" 
 case ".mpg", "mpeg" 
  contenttype = "video/mpeg" 
 case ".rtf" 
  contenttype = "application/rtf" 
 case ".htm", "html" 
  contenttype = "text/html" 
 case ".txt" 
  contenttype = "text/plain" 
 case else 
  contenttype = "application/octet-stream" 
 end select 

 response.addheader "content-disposition", "attachment; filename=" & flname 
 response.addheader "content-length", flsize 

 response.charset = "utf-8" 
 response.contenttype = contenttype 

 response.binarywrite objstream.read 
 response.flush 
 response.clear() 
 objstream.close 
 set objstream = nothing 
%>

将下面的东西存成download.asp然后你就可以用<a herf="http://xxx.xxx.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 

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网