在VBA中下载文件并将其存储 [英] Downloading a file in VBA and storing it

查看:692
本文介绍了在VBA中下载文件并将其存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to download a file that I got from a REST search. The URL is like the following:

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

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

(I needed to edit it due to privacy reasons..)

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

The file is supposed to be a result of a Nastran computation, it can be viewed by a simple Texteditor. The Extension is .pch, it is relatively large (~21mb)

如何在VBA中实现?

推荐答案

首先-链接无效.第二:根据HTTP请求的输出,可以有两种方法.

First of all - the link does not work. Second of all: there can be 2 approaches depending on the output of the HTTP request.

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

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响应,则可以将输出保存到文件中

If the output is a simple text HTML response you can save the output to a file

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

这篇关于在VBA中下载文件并将其存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆