学习网考试学习资料

Gzu521.com

asp中自定义文件下载

ASP教程   点击:次   发布时间:2006-8-30   【字体: 】   来源:Gzu521.com
贵 州 学 习 网
可以用流下载(耗内存,少用)或直接转到该文件. 


<% 

const use_stream = 0 ’0.不用流(adodb.stream)下载 1.用流下载 
const allow_file_ext = "rar,zip,chm,doc,xls,swf,mp3,gif,jpg,jpeg,png,bmp" ’允许下载的文件的扩展名,防止源代码被下载 

dim sdownfilepath ’下载文件路径 
sdownfilepath = trim(request("filepath")) 
’或者根据传过来的文件id从数据库中获取文件路径 

’如果 sdownfilepath 为绝对路径,一定要将 sdownfilepath 转换为相对 本文件的相对路径 

’sdownfilepath = "focus.swf" 

call downloadfile(sdownfilepath) 

function downloadfile(s_downfilepath) 
    ’判断有没传递文件名 
    if isnull(s_downfilepath) = true or trim(s_downfilepath) = "" then 
        outputerr "错误:先确定要下载的文件,下载失败" 
    end if 

    ’判断扩展名是否合法 
    dim s_fileext 
    s_fileext = mid(s_downfilepath, instrrev(s_downfilepath, ".")+1) 
    if instr("," & allow_file_ext & ",", "," & s_fileext & ",") <= 0 then 
        outputerr "错误:文件类型(" & s_fileext & ")不允许被下载,下载失败" 
    end if 
     
    s_downfilepath = replace(s_downfilepath, "\", "/") 

    ’为了安全,某些目录禁止下载文件,在这里处理 
    ’ 
     
    ’检测服务器是否支持fso 
    dim o_fso 
    on error resume next 
    set o_fso = server.createobject("scripting.filesystemobject") 
    if err.number <> 0 then 
        err.clear 
        outputerr "错误:服务器不支持fso组件,下载失败" 
    end if 

    ’取得文件名,文件大小 
    dim s_filemappath 
    dim o_file, s_filename, n_filelength 
    s_filemappath = server.mappath(s_downfilepath) 
    if (o_fso.fileexists(s_filemappath)) = true then 
        set o_file = o_fso.getfile(s_filemappath) 
        s_filename = o_file.name 
        n_filelength = o_file.size 
        o_file.close 
    else 
        outputerr "错误:文件不存在,下载失败" 
    end if 
    set o_fso = nothing 

    ’判断是否下载的文件大小超过限制 
    ’     
     
    ’如果不是用流下载,直接转到该文件 
    if use_stream = 0 then 
        response.redirect sdownfilepath 
        response.end 
    end if 

    ’检测服务器是否支持adodb.stream 
    on error resume next 
    set o_stream = server.createobject("adodb.stream") 
    if err.number <> 0 then 
        err.clear 
        outputerr "错误:服务器不支持adodb.stream组件,下载失败" 
    end if 

    o_stream.tyep = 1 
    o_stream.open 
    o_stream.loadfromfile s_filemappath  

    response.buffer = true 

转,贴.自,D.O,C.5,2.1,资.料,分.享,网.网络编程,ASP教程 www.doc521.com


    response.clear 
    response.addheader "content-disposition", "attachment; filename=" & s_filename 
    response.addheader "content-length", n_filelength  
    response.charset = "utf-8"  
    response.contenttype = "application/octet-stream"  
    response.binarywrite o_stream.read 
    response.flush 

    o_stream.close 
    set o_stream = nothing 

end function 

sub outputerr(s_errmsg) 
    response.write "<font color=red>" & s_errmsg & "</font>"  
    response.end 
end sub 

%> 

责任编辑:gzu521

网络编程分类
ASP教程
.Net教程
Java教程
PHP教程
数据库基础
ACCESS教程
SQL Server教程
MySQL教程
Oracle教程
分类推荐信息
更多...
大类最新文章
更多...