我正在尝试使用 MSExcel 或 MSAccess 中的 VBA 使用用户名和密码从HTTPS站点下载图像。
使用 Windows 照片查看器打开的图像显示以下消息:
Windows 照片查看器无法打开图片,因为文件看起来已损坏、损坏或太大!。
似乎根本没有下载图像。
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
此代码适用于 HTTP 访问。如何修改它以从此 HTTPS 站点下载图像?