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 - Using Streams to save binaries (Page 2 of 5 )
Streams are classes that can be used to read from and write to different storage media like memory, files, blobs and sockets. All stream objects in Delphi are descendants of the abstract TStream class and inherit most of its methods and properties, but each stream can deal with only a single type of media. For instance the TfileStream can be used to read and write to files only.
So we will create a TFileStream object to temporarily store data before it is saved to database. Now let's get to the coding part. On the ButtonClick event of Button1 we will execute the OpenDlg to let the user select a file to upload, and this time we will set the filter of the dialog box to accept all types of files. Then we create the stream object passing the selected file as the parameter so that the file is now loaded into the FileStream.
TBlobField has a member method named "LoadFromStream" which can be used to save data from the stream to the blob field. Call the "Post" method and we are done. The selected file is now saved in the database as a Binary Large Object (Blob). If you have SQL Enterprise Manager you can execute a simple SQL statement in the SQL Query Analyzer to see the raw data in the grid.
Here is the code that saves the file to database.
var fStream:TFileStream;
begin OpenDialog1.Filter:='All Files(*.*)|*.*'; if OpenDialog1.Execute then fStream:=TFileStream.Create(OpenDialog1.FileName,fmOpenRead); ADOTable1.Insert; try TBlobField(ADOTable1.FieldByName('image')).LoadFromStream(fStream); finally fStream.Free; end; ADOTable1.Post; end;