The Good Stuff
Ok, we know how to connect to the database, we know how to insert data into
the database, and we have access to the uploaded image's properties. But how
do we pass the stream of the image to SaveToDB(). Again, .NET comes to the
rescue. With 1 line of code we are able to access the image stream and convert
it to a Byte array.
int n = imgStream.Read(imgBinaryData,0,imgLen);
The stream object provides a method called Read(). Read() takes 3 parameters:
-
buffer - An array of bytes. A maximum of count bytes are
read from the current stream and stored in buffer.
-
offset - The byte offset
in buffer at which to begin storing the data
read from the current stream.
-
count - The maximum number of bytes
to be read from the current stream.
So we pass in our Byte array, imgBinaryData; the place to start at, 0;
and the amount of bytes we want to read. n number of bytes read into
our array
is returned.
Extending beyond images
Because we are able to access the binary stream of data, images are not the
only object we can store in the database. Some other objects might be streaming
video, com objects, or sound clips.
Conclusion
So there we have it, ASP.NET provides us some easy functionality for uploading
images into a database. In Part II, we will actually look at pulling these
images out of a database and sending them to a browser. The complete code
used for this article can be found on the next page.