Reading Binary Files in ASP
My friend Elton came to me with a head-scratcher today. He
needs to be able to have an ASP script return an image to the browser,
so that he can write an HTML page like this:
See how the script is the target of the IMG tag?
The script itself has several steps:
- Connect to a database and do some fancy-schmancy database stuff
- Query the database for the name of the file that contains the actual image.
- Open the file and read its contents
- Emit the file contents (with a “Content-Type” of image/gif) to the browser.
seemed to be working OK, but the image was not displayed in the
page. Instead, he was getting a red-X indicating that the image
could not be found.
It took some digging, but here's what we finally found out:
- The original script used the Scripting.FileSystemObject to open and read the contents of the image file.
some testing (opening a file and then writing it back to a new file) we
determined that the FileSystemObject was at least able to make a
perfect copy of a file.
- HOWEVER, it turns out that the FileSystemObject can't handle binary data!
FSO object model, which is contained in the Scripting type library
(Scrrun.Dll), supports text file creation and manipulation through the
TextStream object. It does not as yet, however, support the creation or
manipulation of binary files.
(from this page on MSDN)
- Microsoft's solution to this problem is to build an ActiveX DLL to handle the Binary Read for you. They even provide source code!
There's a better solution, though (with thanks to PSTRUH Software
for this great tip). The ADODB.Stream object, which is present on
virtually all IIS servers, is able to easily read a binary file.
Here's the code to read a binary file:
Const adTypeBinary = 1
'Create Stream object
Set BinaryStream = CreateObject("ADODB.Stream")
'Specify stream type - we want To get binary data.
BinaryStream.Type = adTypeBinary
'Open the stream
'Load the file data from disk To stream object
'Open the stream And get binary data from the object
ReadBinaryFile = BinaryStream.Read
all that's needed is to put it together. Here's the code to read
the GIF file from disk and hand it back to the browser:
Dim path, gifdata
' Locate the file on disk
path = server.mappath("/images/someImage.gif")
' Read the GIF image data
gifdata = ReadBinaryFile(path)
' Send the GIF image to the browser
Response.ContentType = "image/gif"
Response.Buffer = True
That's it! Hopefully this'll be helpful to somebody. Got a better way? Leave a comment!