2

我需要下载从 REST 搜索中获得的文件。URL 如下所示:

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

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

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

如何在 VBA 中实现?

4

2 回答 2

15

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

如果输出是文件,您可以使用以下代码:

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
于 2015-03-31T11:12:03.753 回答
1

如果文件已经存在于服务器上并且不必通过查询等方式构建,则可以使用如下 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
于 2015-03-31T11:31:22.033 回答