2012-05-08 182 views

回答

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 
%> 
+7

將「MSXML2.XMLHTTP」更改爲「MSXML2.ServerXMLHTTP.3.0」(xmlhttp不適用於ASP服務器代碼)。 – AnthonyWJones

10

我使用了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