Home » excel » excel – How to get file extension using Microsoft XMLHTTP using VBA

excel – How to get file extension using Microsoft XMLHTTP using VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m using the following simple code to download and save some files from the internet. The server that I’m connecting to sometimes generates excel files and the other times text files, I would like to know if theres any possible way to figure out whats the file extension so it can be downloaded with the proper extension? right now I save all of the files as txt files and if the file returns excel files then the downloaded file will be useless (as it is saved as a txt file and I have to change the extension manually). Thanks guys

Dim myURL As String
Dim WinHttpReq As Object
Dim FP As String

myURL = "SAMPLE URL"

Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.Send

myURL = WinHttpReq.ResponseBody
If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.ResponseBody
    oStream.SaveToFile (FP & "\" & C1 & "-" & C2 & ".txt"), 2
    oStream.Close
End If

End Sub
How to&Answers:

Before WinHttpReq.Open “GET”, myUrl, false you can try to open the header and look at the mime type of your file before downloading it:

WinHttpReq.Open "HEAD", myUrl, false
WinHttpReq.Send
MyHeader = WinHttpReq.getAllResponseHeaders()
' Scan MyHeader here to find your file mime type ...

Answer:

Thanks to kiks73 I find my way to deal with this issue, However I wanted to add a little part to it, using

MyHeader = WinHttpReq.getAllResponseHeaders()

will give you something like

“Server: Microsoft-IIS/5.0
Date: Tue, 29 Jul 2014 18:05:44 GMT
X-Powered-By: ASP.NET
Content-Disposition: FileName=11120166.Txt
Content-Type: application/octet-stream
Content-Length: 152
Content:

which might be a bit hard to read and analyze so I found the alternative way of getting only the file name and extension:

MyHeader = WinHttpReq.getResponseHeader("Content-Disposition")

this way you ditch all the junk and get only what youre looking for. HOWEVER: in my case I have to download between 300 to 8000 files at once (all of the same type, but the type may change from one session to another one) and trying to pull extension each time seems absurd, and it make my code crash, so you may wanna pull the extension only once.
Thanks again kiks73 for helping me out