Dynamically loading/saving images from a database in ASP.NET
The other day I was working on a web page and I needed to get images from the DB displayed on the web page. Using a the file upload control, its pretty easy to save content:
Protected Sub btnSavePicture_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSavePicture.Click
Dim pictureTA As New MyTableAdapters.PictureTableAdapter()
Dim imageStream As IO.Stream = picUpload.PostedFile.InputStream
Dim imageData(picUpload.PostedFile.ContentLength) As Byte
imageStream.Read(imageData, 0, picUpload.PostedFile.ContentLength)
pictureTA.UpdatePicture(imageData, id)
End Sub
Then suppose you have another page that needs to display the picture. You can set an asp Image control's ImageUrl to a another page which retrieves the image: myPicure.ImageUrl = "ImageLoader.aspx"
In the Page_Load event of ImagerLoader.aspx, just retrieve the content from the DB and stream the content type back to the client like so:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim pictureTA As New MyTableAdapters.PictureTableAdapter()
Dim pic As Image = pictureTA.GetPicture(id)
If Not pic Is DBNull.Value Then
Response.ContentType = "image/gif"
Response.BinaryWrite(pic)
End If
End Sub
Even though I prefer developing in C#, VB.NET makes things so much simpler at times. If I would have been using C# at the time I probably would have had a dozen cast statements litered throughout. Thanks to my 3 word per minute typing speed, those cast statements really add up.