Downloading png to disk creates broken file - ms-access

In my project, I want to download a png file from a url and save it to disk.
I have a url to an image, and I can load it in my web browser without any problem.
But when I use Access to download this file and save it, it saves "a" file, but it doesn't seem to have any image. Every file it creates is 167kb, and I cannot view them with my graphics viewers (XnViewMP, for example).
When I load the created file with PE Studio, it says the MZ signature is missing (I'm not sure that means anything).
I've tried this with an .ico file on my local webserver, too, and have the same issue.
Here is the code I'm using to download the image file.
Public Function DownloadFile(whaturl As String, whatdestination As String) As Boolean
Dim newfilepath
Dim success As Boolean
Dim WinHttpReq: Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", whaturl, False
WinHttpReq.Send
If WinHttpReq.Status = 200 Then
Dim oStream: Set oStream = CreateObject("ADODB.Stream")
oStream.type = 1 '1 is binary
oStream.Open
oStream.Write WinHttpReq.ResponseBody
oStream.SaveToFile whatdestination, 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
success = True
Else
success = False
End If
DownloadFile = success
End Function
Maybe someone can tell my why this code seems to fail in downloading the png file? I've tried with an .ico file, too, and have the same problem. Maybe someone can help me with this code?

You are making it too hard. Use a function like this:
Option Compare Database
Option Explicit
' API declarations.
'
Private Declare Function URLDownloadToFile Lib "Urlmon" Alias "URLDownloadToFileA" ( _
ByVal pCaller As Long, _
ByVal szURL As String, _
ByVal szFileName As String, _
ByVal dwReserved As Long, _
ByVal lpfnCB As Long) _
As Long
' Download a file or a page with public access from the web.
' Returns 0 if success, error code if not.
'
' If parameter NoOverwrite is True, no download will be attempted
' if an existing local file exists, thus this will not be overwritten.
'
' Examples:
'
' Download a file:
' Url = "https://www.codeproject.com/script/Membership/ProfileImages/%7Ba82bcf77-ba9f-4ec3-bbb3-1d9ce15cae23%7D.jpg"
' FileName = "C:\Test\CodeProjectProfile.jpg"
' Result = DownloadFile(Url, FileName)
'
' Download a page:
' Url = "https://www.codeproject.com/Tips/1022704/Rounding-Values-Up-Down-By-Or-To-Significant-Figur?display=Print"
' FileName = "C:\Test\CodeProject1022704.html"
' Result = DownloadFile(Url, FileName)
'
' Error codes:
' -2146697210 "file not found".
' -2146697211 "domain not found".
' -1 "local file could not be created."
'
' 2004-12-17. Gustav Brock, Cactus Data ApS, CPH.
' 2017-05-25. Gustav Brock, Cactus Data ApS, CPH. Added check for local file.
' 2017-06-05. Gustav Brock, Cactus Data ApS, CPH. Added option to no overwrite the local file.
'
Public Function DownloadFile( _
ByVal Url As String, _
ByVal LocalFileName As String, _
Optional ByVal NoOverwrite As Boolean) _
As Long
Const BindFDefault As Long = 0
Const ErrorNone As Long = 0
Const ErrorNotFound As Long = -1
Dim Result As Long
If NoOverwrite = True Then
' Page or file should not be overwritten.
' Check that the local file exists.
If Dir(LocalFileName, vbNormal) <> "" Then
' File exists. Don't proceed.
Exit Function
End If
End If
' Download file or page.
' Return success or error code.
Result = URLDownloadToFile(0, Url & vbNullChar, LocalFileName & vbNullChar, BindFDefault, 0)
If Result = ErrorNone Then
' Page or file was retrieved.
' Check that the local file exists.
If Dir(LocalFileName, vbNormal) = "" Then
Result = ErrorNotFound
End If
End If
DownloadFile = Result
End Function
taken from my article: Show pictures directly from URLs in Access forms and reports
(If you don't have an account, browse for the link: Read the full article)
Full code is also at GitHub: VBA.PictureUrl

Related

Image scraping in access

I have generated data matrix by using Access vba. Now I have to scrape that generated pic into my form each and everytime. Here is the code. Half part is generating barcode while half to scrape that picture in Access form is not working.
Private Sub Command24_Click()
Dim IE As New InternetExplorer
IE.Visible = True
IE.Navigate ("https://barcode.tec-it.com/en/DataMatrix?data=" & Forms!QRcodes!Text)
Do
DoEvents
Loop Until IE.ReadyState = READYSTATE_COMPLETE
StatusBar = "loading webpage...."
Dim img As Object
Dim html As HTMLDocument
Set html = IE.Document
Dim elementcol As Object, link As Object
Set elementcol = html.getElementsByTagName("img")
Dim doc As Object
Forms!QRcodes!OLEBound34 = elementcol
'Set img = ele.getElementsByTagName("img")
Set Tables!QRcodes!Matrix = elementcol
MsgBox "Getting Code"
End Sub
Grab the skeleton for the full URL to only the generated picture (as displayed on the site) - for example:
https://barcode.tec-it.com/barcode.ashx?data=12345678&code=DataMatrix&multiplebarcodes=false&translate-esc=false&unit=Fit&dpi=96&imagetype=Gif&rotation=0&color=%23000000&bgcolor=%23ffffff&qunit=Mm&quiet=0&dmsize=Default' alt='Barcode Generator TEC-IT
Then you can use my code and demo published in one of my articles:
Show pictures directly from URLs in Access forms and reports
The two main functions downloads pictures directly, one is caching the download:
' Download a file or a page with public access from the web as a cached file of Internet Explorer.
' Returns the full path of the cached file if success, an empty string if not.
'
' Examples:
'
' Download a file:
' Url = "https://www.codeproject.com/script/Membership/ProfileImages/%7Ba82bcf77-ba9f-4ec3-bbb3-1d9ce15cae23%7D.jpg"
' Result = DownloadCacheFile(Url)
' Result -> C:\Users\UserName\AppData\Local\Microsoft\Windows\INetCache\IE\B2IHEJQZ\{a82bcf77-ba9f-4ec3-bbb3-1d9ce15cae23}[2].png
'
' Download a page:
' Url = "https://www.codeproject.com/Tips/1022704/Rounding-Values-Up-Down-By-Or-To-Significant-Figur?display=Print"
' Result = DownloadCacheFile(Url)
' Result -> C:\Users\UserName\AppData\Local\Microsoft\Windows\INetCache\IE\B2IHEJQZ\Rounding-Values-Up-Down-By-Or-To-Significant-Figur[1].htm
'
' 2017-05-25. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DownloadCacheFile( _
ByVal Url As String) _
As String
Const BufferLength As Long = 1024
Const BindFDefault As Long = 0
Const ErrorNone As Long = 0
Dim FileName As String
Dim LocalFileName As String
Dim Result As Long
' Create buffer for name of downloaded and/or cached file.
FileName = Space(BufferLength - 1) & vbNullChar
' Download file or page.
' Return name of cached file in parameter FileName.
Result = URLDownloadToCacheFile(0, Url & vbNullChar, FileName, BufferLength, BindFDefault, 0)
' Trim file name.
LocalFileName = Split(FileName, vbNullChar)(0)
DownloadCacheFile = LocalFileName
End Function
I tested with a few URLs, and the codes were displayed at once:

MS ACCESS webbrowser control file preview not working properly

I've been trying to display files in a form using the webbrowser control and have had some success when displaying pdf's, however, if I want to display a TIFF file it wants to download the picture rather than displaying it.
I suppose the question I am asking is if the webbrowser control can display TIFF files. Is there a workaround?
Cheers
Eych
You may need a more advanced picture control like csXImage to display TIFF pictures.
The file, you can download with my DownloadFile function found in my article here:
Show pictures directly from URLs in Access forms and reports
and also on GitHub: VBA.PictureUrl
Option Compare Database
Option Explicit
' API declarations.
'
Private Declare Function URLDownloadToFile Lib "Urlmon" Alias "URLDownloadToFileA" ( _
ByVal pCaller As Long, _
ByVal szURL As String, _
ByVal szFileName As String, _
ByVal dwReserved As Long, _
ByVal lpfnCB As Long) _
As Long
' Download a file or a page with public access from the web.
' Returns 0 if success, error code if not.
'
' If parameter NoOverwrite is True, no download will be attempted
' if an existing local file exists, thus this will not be overwritten.
'
' Examples:
'
' Download a file:
' Url = "https://www.codeproject.com/script/Membership/ProfileImages/%7Ba82bcf77-ba9f-4ec3-bbb3-1d9ce15cae23%7D.jpg"
' FileName = "C:\Test\CodeProjectProfile.jpg"
' Result = DownloadFile(Url, FileName)
'
' Download a page:
' Url = "https://www.codeproject.com/Tips/1022704/Rounding-Values-Up-Down-By-Or-To-Significant-Figur?display=Print"
' FileName = "C:\Test\CodeProject1022704.html"
' Result = DownloadFile(Url, FileName)
'
' Error codes:
' -2146697210 "file not found".
' -2146697211 "domain not found".
' -1 "local file could not be created."
'
' 2004-12-17. Gustav Brock, Cactus Data ApS, CPH.
' 2017-05-25. Gustav Brock, Cactus Data ApS, CPH. Added check for local file.
' 2017-06-05. Gustav Brock, Cactus Data ApS, CPH. Added option to no overwrite the local file.
'
Public Function DownloadFile( _
ByVal Url As String, _
ByVal LocalFileName As String, _
Optional ByVal NoOverwrite As Boolean) _
As Long
Const BindFDefault As Long = 0
Const ErrorNone As Long = 0
Const ErrorNotFound As Long = -1
Dim Result As Long
If NoOverwrite = True Then
' Page or file should not be overwritten.
' Check that the local file exists.
If Dir(LocalFileName, vbNormal) <> "" Then
' File exists. Don't proceed.
Exit Function
End If
End If
' Download file or page.
' Return success or error code.
Result = URLDownloadToFile(0, Url & vbNullChar, LocalFileName & vbNullChar, BindFDefault, 0)
If Result = ErrorNone Then
' Page or file was retrieved.
' Check that the local file exists.
If Dir(LocalFileName, vbNormal) = "" Then
Result = ErrorNotFound
End If
End If
DownloadFile = Result
End Function

External Images in Access Form

I have a dataset with an Image URL that links to a picture of the item in each record. I'd like to create a form so I can look at the data associated with the item and see a picture of it. I'm fairly new to Access and can't seem to figure out how to get the external image to show up.
Thanks for the help!
You can download the pictures transparently to the browser cache and then load them from the cache to be displayed:
' Download (picture) file from a URL of a hyperlink field to a
' (temporary) folder, and return the full path to the downloaded file.
'
' This can be used as the control source for a bound picture control.
' If no Folder is specified, the user's IE cache folder is used.
'
' Typical usage in the RecordSource for a form or report where Id is
' the unique ID and Url is the hyperlink field holding the URL to
' the picture file to be displayed:
'
' - to a cached file where parameter Id is not used:
'
' Select *, UrlContent(0, [Url]) As Path From SomeTable;
'
' - or, where Id is used to create the local file name:
'
' Select *, UrlContent([Id], [Url], "d:\somefolder") As Path From SomeTable;
'
' Then, set ControlSource of the bound picture control to: Path
'
' 2017-05-28. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function UrlContent( _
ByVal Id As Long, _
ByVal Url As String, _
Optional ByVal Folder As String) _
As Variant
Const NoError As Long = 0
Const Dot As String = "."
Const BackSlash As String = "\"
Dim Address As String
Dim Ext As String
Dim Path As String
Dim Result As String
' Strip leading and trailing octothorpes from URL string.
Address = HyperlinkPart(Url, acAddress)
' If Address is a zero-length string, Url was not wrapped in octothorpes.
If Address = "" Then
' Use Url as is.
Address = Url
End If
If Folder = "" Then
' Import to IE cache.
Result = DownloadCacheFile(Address)
Else
If Right(Folder, 1) <> BackSlash Then
' Append a backslash.
Folder = Folder & BackSlash
End If
' Retrieve extension of file name.
Ext = StrReverse(Split(StrReverse(Address), Dot)(0))
' Build full path for downloaded file.
Path = Folder & CStr(Id) & Dot & Ext
If DownloadFile(Address, Path) = NoError Then
Result = Path
End If
End If
UrlContent = Result
End Function
The helper functions and the full explanation and a demo can be found here:
Show pictures directly from URLs in Access forms and reports
Code is also at GitHub: VBA.PictureUrl

Import a CSV file into Access database from SharePoint Online Document Library

I have a CSV file uploaded in a SharePoint Online Document Library that gets updated on a daily basis. I use this CSV file to create some reports with Access Database. What I would like to achieve is to import the CSV file into Access automatically without the need to download and save the CSV file locally. The code I'm using is as follows:
Sub ImportCSV()
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="Daily_Report_Table", FileName:="https://mycompany.sharepoint.com/teams/Daily%20Reporting.csv", HasFieldNames:=True
End Sub
However, it either asks me to log in and then it says I don't have access to the file or doesn't execute saying it cannot load HTML page...
Don't be fooled by the title of the link.
You cannot import/link a file directly via HTTP. The code downloads the file for you, ready to be linked:
Sub ImportCSV()
Dim Result As Long
Dim Url As String
Dim Filename As String
Url = "https://mycompany.sharepoint.com/teams/Daily%20Reporting.csv"
Filename = "C:\Imports\DailyReporting.csv"
Result = DownloadFile(Url, Filename)
If Result = 0 Then
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="Daily_Report_Table", FileName:=Filename, HasFieldNames:=True
End If
End Sub
Supporting code module:
Option Compare Database
Option Explicit
Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" ( _
ByVal pCaller As Long, _
ByVal szURL As String, _
ByVal szFileName As String, _
ByVal dwReserved As Long, _
ByVal lpfnCB As Long) _
As Long
Public Function DownloadFile( _
ByVal strURL As String, _
ByVal strLocalFilename As String) _
As Long
' Download file or page with public access from the web.
' 2004-12-17. Cactus Data ApS, CPH.
' Usage, download a file:
' lngRet = DownloadFile("http://www.databaseadvisors.com/Graphics/conf2002/2002ConferencePicsbySmolin/images/dba02smolin27.jpg", "c:\happybassett.jpg")
'
' Usage, download a page:
' lngRet = DownloadFile("http://www.databaseadvisors.com/conf2002/conf200202.asp", "c:\dbaconference.htm")
' Returns 0 if success, error code if not.
' Error codes:
' -2146697210 "file not found".
' -2146697211 "domain not found".
' Limitation.
' Does not check if local file was created successfully.
Dim lngRetVal As Long
lngRetVal = URLDownloadToFile(0, strURL & vbNullChar, strLocalFilename & vbNullChar, 0, 0)
DownloadFile = lngRetVal
End Function

get list of files from path on the internet

i'm automating a project where every month i need to go on a website and copy a file from there.
i'm able to copy the file, the problem is that they're named like below so there's no way for me to know which file to copy that month.
filename2015011023549.zip
filename2015021922876.zip
is there a way to get a list of files from a website?
You download the page (see in-line comments) with the file listing to a local file, then parse that file for possible file name candidates:
Option Compare Database
Option Explicit
Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" ( _
ByVal pCaller As Long, _
ByVal szURL As String, _
ByVal szFileName As String, _
ByVal dwReserved As Long, _
ByVal lpfnCB As Long) _
As Long
Public Function DownloadFile( _
ByVal strURL As String, _
ByVal strLocalFilename As String) _
As Long
' Download file or page with public access from the web.
' 2004-12-17. Cactus Data ApS, CPH.
' Usage, download a file:
' lngRet = DownloadFile("http://www.databaseadvisors.com/Graphics/conf2002/2002ConferencePicsbySmolin/images/dba02smolin27.jpg", "c:\happybassett.jpg")
'
' Usage, download a page:
' lngRet = DownloadFile("http://www.databaseadvisors.com/conf2002/conf200202.asp", "c:\dbaconference.htm")
' Returns 0 if success, error code if not.
' Error codes:
' -2146697210 "file not found".
' -2146697211 "domain not found".
' Limitation.
' Does not check if local file was created successfully.
Dim lngRetVal As Long
lngRetVal = URLDownloadToFile(0, strURL & vbNullChar, strLocalFilename & vbNullChar, 0, 0)
DownloadFile = lngRetVal
End Function