views:

185

answers:

2

I'm currently patching an asp.net program where I need to be able to send an image to an SQL Server 2005 DB. It works fine when I use the asp:fileupload control, but the trick is that when the user deletes the image, I'm supposed to replace it with an image from the server saying "empty", in code-behind.

I know how to open, use and save text files in vb, but I can't find any information anywhere on how to open an image / binary file in a similar manner so that I can use it as an sql-parameter on the update query.

Below is an example of how easy it is to use a file from the fileupload control.


            Dim t_id As Integer = Convert.ToInt32(Request.QueryString("id"))

            open()

            Dim picture As New SqlParameter("@picture", pictureFileUpload.FileBytes)
            Dim id As New SqlParameter("@id", t_id)

            myCommand = New SqlCommand("spChangeImage")
            myCommand.CommandType = CommandType.StoredProcedure
            myCommand.Connection = conn

            myCommand.Parameters.Add(picture)
            myCommand.Parameters.Add(id)

            myCommand.ExecuteNonQuery()
            close()

Now I need a way to open an image file and set it as a parameter in a similar manner, but I've no clue as to how to go about doing that. All the search results are focused on opening and viewing an image in html, I just need the binary to use it in the query. I'm trying to use binaryreader but even then I've no idea how to actually map the file to begin with.

Thanks in advance for any help!

+1  A: 

this might help.

Canavar
+1  A: 

Personally, I wouldn't store this image in the database when the user deletes their value. I would set the column to null. When writing the image I would detect if the column is null, then read the file and write it to the response. If you do this, then you won't need to accumulate anything into a local buffer, you can just write each buffer to the response as it is read. You can use FileInfo.Length to determine the content length of the response.

If you insist on putting the image in the DB, you can also use FileInfo.Length to determine the size of buffer you need to hold the image. Use your BinaryReader to read this length of bytes into the buffer. The buffer then becomes your parameter to the SQL command.

tvanfosson
At first I thought I couldn't do this since the absence of the picture produced a whole new dimension of problems. But a colleague then showed along a similar idea how to replace the "NULL" file at the source right after the DB connection, so the rest of the program figured everythign worked as intended. The program wasn't originally built to handle missing pictures at all. ;) Thanks for this.
Zan