I did a search for uploading an image (or any file) using LINQ TO SQL and could not find a blog or article. Here is a quick note on how to do this. The following code assumes that you have a "FileUpload" control on your webform. I'm using a stored procedure to add a row to my "Users" table. I have a column named "Photo". The sql server datatype for Photo column is "Image".
This is my stored procedure.
create proc dbo.usp_user_updateimage
(
@userid uniqueidentifier,
@photo image
)
as
set nocount on
update dbo.users set
photo = @photo
where
userid = @userid
This method is from the code behind of my webform which has a FileUpload control on it. It's the click event for a button labeled "btnAddPhoto".
Protected Sub btnAddPhoto_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddPhoto.Click
If Page.IsValid Then
'photoFileUpload is the FileUpload control
If photoFileUpload.HasFile AndAlso photoFileUpload.PostedFile.ContentLength > 0 Then
' convert the fileupload.postedfile to system.data.linq.binary
Dim fileArray(photoFileUpload.PostedFile.ContentLength) As Byte
fileArray(photoFileUpload.PostedFile.ContentLength) = New Byte()
photoFileUpload.PostedFile.InputStream.Read(fileArray, 0, photoFileUpload.PostedFile.ContentLength)
Dim image As System.Data.Linq.Binary = New System.Data.Linq.Binary(fileArray)
Dim db As New MyDataContext
db.usp_user_updateimage(userId, image)
End If
End If
End Sub
This is a derived code example so the most important thing to remember from this example is the conversion of the FileUpload.PostedFile type to the System.Data.Linq.Binary type. You're basically converting the InputStream to a byte array and then passing the byte array to the System.Data.Linq.Binary constructor.
Technorati Tags: LINQ,LINQ TO SQL,.NET 3.5, System.Data.Linq.Binary
posted @ Sunday, January 27, 2008 8:10 PM