正在下载 VBA 中的文件并存储它

Downloading a file in VBA and storing it

我需要下载一个通过 REST 搜索获得的文件。 URL 如下所示:

https://abc.def/geh/servlet/rest/vault?oid=xxx&expr=files.file1

(出于隐私原因,我需要对其进行编辑..)

该文件应该是 Nastran 计算的结果,可以通过简单的文本编辑器查看。扩展名为.pch,比较大(~21mb)

如何在 VBA 中实施?

首先 - link 不起作用。其次:根据 HTTP 请求的输出,可以有两种方法。

如果输出是文件你可以使用下面的代码:

Sub DownloadFile(url As String, filePath As String)

    Dim WinHttpReq As Object, attempts As Integer
    attempts = 3
    On Error GoTo TryAgain
TryAgain:
    attempts = attempts - 1
    Err.Clear
    If attempts > 0 Then
        Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
        WinHttpReq.Open "GET", url, False
        WinHttpReq.send

        If WinHttpReq.Status = 200 Then
            Set oStream = CreateObject("ADODB.Stream")
            oStream.Open
            oStream.Type = 1
            oStream.Write WinHttpReq.responseBody
            oStream.SaveToFile filePath, 2 ' 1 = no overwrite, 2 = overwrite
            oStream.Close
        End If
    End If
End Sub

如果输出是简单的文本HTML响应,您可以将输出保存到文件

Function GetXMLHTTPResult(url As String)
    Dim XMLHTTP As Object, attempts As Integer
    attempts = 3
    On Error GoTo TryAgain
TryAgain:
    attempts = attempts - 1
    Err.Clear
    If attempts > 0 Then
        Set XMLHTTP = CreateObject("MSXML2.serverXMLHTTP")
        XMLHTTP.Open "GET", url, False
        XMLHTTP.setRequestHeader "Content-Type", "text/xml"
        XMLHTTP.setRequestHeader "Cache-Control", "no-cache"
        XMLHTTP.setRequestHeader "Pragma", "no-cache"
        XMLHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0"
        XMLHTTP.send
        GetXMLHTTPResult = XMLHTTP.ResponseText
    End If
End Function
Sub SaveFile(url)
        res = GetXMLHTTPResult(url)
        Open "C:\res.txt" For Output As #1
        Write #1, res
        Close #1
End Sub

如果文件已经存在于服务器上并且不必通过查询等方式构建,您可以使用 API 调用,如下所示:

Option Explicit

#If VB7 Then
    Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
    (ByVal pCaller As LongPtr, ByVal szURL As String, ByVal szFileName As String, _
    ByVal dwReserved As LongPtr, ByVal lpfnCB As LongPtr) As Long
#Else
    Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
    (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
    ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#End If

Sub SO()

Dim fileURL As String, saveLocation As String

fileURL = "https://abc.def/geh/servlet/rest/vault?oid=xxx&expr=files.file1"
saveLocation = "C:\Users\bloggsj\desktop\files.file1"

MsgBox "Download completed: " & (URLDownloadToFile(0, fileURL, saveLocation, 0, 0) = 0)

End Sub