0

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?

Community
  • 1
  • 1
sifar
  • 1,086
  • 1
  • 17
  • 43
  • I can't see any Excel or Excel VBA specifics in there. There may be some Access VBA there but I don't use Access so may be wrong. Please drop the Excel tag though. – Mark Fitzgerald Mar 20 '17 at 12:07
  • Hi @MarkFitzgerald this VBA code was in an Excel file, so the tag. However, i think it should work in Access too as it is not Access specific. Let me know if you still want me to remove the tags. – sifar Mar 20 '17 at 12:39
  • OK, You could use it in either Excel or Access VBA so maybe the excel-vba or access-vba tags would be better than the application tags? – Mark Fitzgerald Mar 20 '17 at 12:57
  • @MarkFitzgerald done. – sifar Mar 20 '17 at 14:14

0 Answers0