使用经典ASP从URL下载文件

时间:2012-05-08 10:15:40

标签: asp-classic

我有几个链接到pdf示例的网址

abc.com/1.pdf abc.com/2g.pdf abc.com/i8.pdf

我想要做的是使用经典ASP在文件夹中自动下载PDF

我尝试使用此代码http://blog.netnerds.net/2007/01/classic-asp-push-file-downloads-from-directory-outside-of-the-web-root/ 但这对Http不起作用,如果文件是本地文件,它就可以正常工作。

我想自动完成。

2 个答案:

答案 0 :(得分:11)

我使用了user580950发布的代码和AnthonyWJones的评论,并创建了代码的函数版本。调用该函数,它返回下载文件的内容类型,如果找不到文件,则返回空字符串。

public function SaveFileFromUrl(Url, FileName)
    dim objXMLHTTP, objADOStream, objFSO

    Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.3.0")

    objXMLHTTP.open "GET", Url, false
    objXMLHTTP.send()

    If objXMLHTTP.Status = 200 Then 
        Set objADOStream = CreateObject("ADODB.Stream")
        objADOStream.Open
        objADOStream.Type = 1 'adTypeBinary

        objADOStream.Write objXMLHTTP.ResponseBody
        objADOStream.Position = 0 'Set the stream position to the start

        Set objFSO = Createobject("Scripting.FileSystemObject")
        If objFSO.Fileexists(FileName) Then objFSO.DeleteFile FileName
        Set objFSO = Nothing

        objADOStream.SaveToFile FileName
        objADOStream.Close
        Set objADOStream = Nothing

        SaveFileFromUrl = objXMLHTTP.getResponseHeader("Content-Type")
    else
        SaveFileFromUrl = ""
    End if

    Set objXMLHTTP = Nothing
end function

答案 1 :(得分:5)

如果有人想使用它,我会在互联网上的某处获得此代码。

<%
Server.ScriptTimeout = 60 * 20
' Set your settings
strFileURL = "http://pathtofile.zip"
strHDLocation = "c:\filename.zip"

' Fetch the file
Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.3.0")

objXMLHTTP.Open "GET", strFileURL, False
objXMLHTTP.Send()

If objXMLHTTP.Status = 200 Then
    Set objADOStream = CreateObject("ADODB.Stream")
    objADOStream.Open
    objADOStream.Type = 1 'adTypeBinary

    objADOStream.Write objXMLHTTP.ResponseBody
    objADOStream.Position = 0 'Set the stream position to the start

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    If objFSO.FileExists(strHDLocation) Then objFSO.DeleteFile strHDLocation
    Set objFSO = Nothing

    objADOStream.SaveToFile strHDLocation
    objADOStream.Close
    Set objADOStream = Nothing
End if

Set objXMLHTTP = Nothing
%>