sábado, fevereiro 18, 2006

Como forçar o download de um arquivo em uma página ASP, programando em VBScript

Problema:

Utilizar um algoritmo em VBScript que force o download de um arquivo, ao invés de se utilizar acesso direto à URL do mesmo.

Solução:

Function downloadFile (strFileName)

    ' Caminho físico do arquivo no servidor
    strFilePath = Server.MapPath("/Files/" & strFileName)

    Response.Clear

    Dim oStr
    Dim fso, f, sizeof

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.GetFile( strFilePath )

    SizeOf = f.Size

    Set f = nothing
    Set fso = nothing
    Set oStr = server.CreateObject("ADODB.Stream")

    oStr.Open
    oStr.LoadFromFile strFilePath

    Response.ContentType = "application/x-download"
    Response.AddHeader "content-disposition", "attachment;filename=" & strFileName
    Response.AddHeader "Content-Length", SizeOf

    Dim Buff

    Do Buff = oStr.ReadText(1024)
        Response.BinaryWrite buff
        Response.Flush
    Loop Until IsNull(buff) or buff = ""
End Function