下载文件时防止文件在线打开
来源: | 编辑:TengGao | 发布时间:2014/7/11

今天应一客户要求,在他网站的新产品详细页面做两个功能按钮,一个是在线浏览对应产品的pdf文件,另一个是点击后自动弹出保存文件对话框!


以下是防止文件在线打开代码:

把下面代码保存为asp文件,如:Downlad.asp;

使用时把要下载的文件路径传给此页面就可以了,

例:http://www.tanggao.met/Download.asp?FileUrl=images/fileName.pdf


注:此代码只做功能说明,因为代码对其他文件一样有效,所以实际使用中要对重要文件做过渡处理,如:网站源码文件(asp、php、aspx等)以及数据库文件,不然你的网站源码和数据库会被下载,后台被破解等!!


<%
'防止下载时文件在线打开
'www.tenggao.net
FileUrl=trim(request("file"))
'-----------------------------------------------------------------------------------------------------------------------------------------
'FileUrl 指定要下载的文件路径
Function downloadFile(FileUrl) 
	if FileUrl="" or isnull(FileUrl) then  
		Response.Write("缺少参数...")  
		Response.End 
	end if  
	FileUrlname = server.MapPath(FileUrl)  
	'response.write FileUrlname
	'response.end
	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(FileUrlname) then  
			Response.Write("Error:" & FileUrlname & " 文件不存在")  
			Response.End 
		end if  
		Set f = fso.GetFile(FileUrlname)  
		intFilelength = f.size  
		s.LoadFromFile(FileUrlname)  
		if err then  
			Response.Write("Error:" & err.Description & " ")  
			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
'-----------------------------------------------------------------------------------------------------------------------------------------
call downloadFile(FileUrl)'调用自定义函数
%>

用手机扫描 用手机扫描 用手机扫描