I am trying to download images from an HTTPS site using Username and password using VBA from MSExcel or MSAccess.
The image when opened with Windows Photo Viewer shows the following message:
Windows Photo Viewer can't open the picture because the file appears to damaged, corrupted or is too large!.
It seems the image is not downloaded at all.
Option Explicit
Sub SaveFileFromURL()
Dim FileData() As Byte
Dim FileNum As Long
Dim WHTTP As Object
Dim mainUrl As String, fileUrl As String, filePath As String, myuser As String, mypass As String
Dim strAuthenticate As String
mainUrl = "https://secure.brandbank.com/login.aspx?"
fileUrl = "https://productlibrary.brandbank.com/image/gallerylarge/3520198"
' OR fileUrl = "https://productlibrary.brandbank.com/LabelImage/ViewLabel?pvid=3520198"
filePath = "D:\DOWNLOADS\SYS\test.jpg"
' dummy UN, PW
myuser = "admin"
mypass = "Password"
'strAuthenticate = "start-url=%2F&user=" & myuser & "&password=" & mypass & "&switch=Log+In"
'strAuthenticate = "txtemail=myuser&txtpassword=mypass&cookieCheck=true"
Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5.1")
'I figured out that you have to POST authentication string to the main website address not to the direct file address
WHTTP.Option(6) = False 'WinHttpRequestOption_EnableRedirects
WHTTP.Open "POST", mainUrl, False 'WHTTP.Open "POST", fileUrl, False
'WHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
WHTTP.SetRequestHeader "Content-Type", "multipart/form-data"
'WHTTP.Send strAuthenticate
'Then you have to GET direct file url
WHTTP.Open "GET", fileUrl, False, myuser, mypass
WHTTP.Send
FileData = WHTTP.ResponseBody
Set WHTTP = Nothing
'Save the file
FileNum = FreeFile
Open filePath For Binary Access Write As #FileNum
Put #FileNum, 1, FileData
Close #FileNum
MsgBox "File has been saved!", vbInformation, "Success"
End Sub
This code works with HTTP access. How do I modify it to download images from this HTTPS site?