Saving Images and Binary Files to a Database with Delphi 2
In my previous article I talked about ADO Components and how to use them to conduct database transactions from our application. We created a small application to save bitmap files to a database and retrieve them using the data-aware TDBImage component. In this article you'll learn how to save other types of files.
Saving Images and Binary Files to a Database with Delphi 2 (Page 1 of 5 )
DBImage is compatible with bitmaps only so if you want to save and retrieve other image formats like JPEGs you cannot use the DBImage component. Instead you will have to use the TImage component and add the JPEG unit to the "uses" clause of the unit. Since the TImage component is not data-aware and is not linked to the blob field in the database, we would have to post the image by first loading it to a stream object and then saving the stream data to the database.
With this approach we are trying to save files as raw binary data without worrying about the format to which they belong. Now if we were to use this approach to save JPEGs shouldn't we widen the scope to include other file types too ? Surely, when given an option, the user may want to save GIF, pdf, doc and zip files too.
Saving Binary Files
So let us start with saving binary files to a database. As you might have already noticed we are saving files to a BLOB (Binary Large Object) field. BLOB fields are fields which store large chunks of data of varying formats and indefinite size as opposed to simple data types.
The BLOB column saves data as binary strings or byte strings and cannot be searched. The TBlobField class in Delphi can not only contain raw data of arbitrary length but also provides methods to manipulate raw binary data and files. For instance you can copy raw binary data between a BLOB field and a binary file by calling methods of the TBlobField class. One of these methods of the TBlobField class is the "LoadFromFile" method which can be called to save data from a file to the database without much effort. We can modify the example code from the previous article to include this method instead of loading the image to DBImage component.
begin OpenDialog1.Filter:='*.bmp|*.bmp'; if OpenDialog1.Execute then begin TBlobField(ADOTable1.FieldByName('Image')). LoadFromFile(OpenDialog1.FileName); end; end;
Make sure you have set ADOTable1 to insert mode by using the DBNavigator and after the OpenDialog exits click the "a" (tick) button to save all fields. Navigate the dataset; you will find that the image you inserted last shows up on the DBImage component. I tried saving files other than bitmaps using the same method but it didn't work; nor could I find any information on whether it should. May be I did not search diligently enough but I was not concerned with the issue, since I intended to use streams to save the files and retrieve for reasons I will elucidate later on in this article.