Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

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: ,,.NET 3.5, System.Data.Linq.Binary

posted @ Sunday, January 27, 2008 8:10 PM

Print

Comments on this entry:

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by Derick at 3/1/2008 7:04 PM
Gravatar
Thanks for this.

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by Chris at 3/1/2008 7:16 PM
Gravatar
Thanks for the comments. Glad I could help.

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by Pranil at 4/11/2008 1:56 PM
Gravatar
exactly what i was looking for
thanks!

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by James South at 4/20/2008 8:59 PM
Gravatar
Thanks for the article. It's the only one I've found so far. To further this, how would I bind the image binary to an asp image so that the image is updated on file upload pror to saving. I want to update the image, then save the information later as part of a larger record using the default update in a details view.(I've got the rest of my record saving nicely).

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by murtuza at 4/22/2008 8:12 AM
Gravatar
Its very nice i give thanks from heart

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by Morten at 5/5/2008 4:38 AM
Gravatar
Great stuff, helped me out a lot, thanks.

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by Nilay at 10/2/2008 1:52 PM
Gravatar
excellent...

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by dudemeister at 10/15/2008 11:44 AM
Gravatar
thanks for this. didnt know i had to convert to a linq.Binary type. and would have taken ages to figure it out.

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by ashkan at 10/21/2008 1:14 PM
Gravatar
tnx man.
i always use your articles. they are simply the best.
will you give some code from retrieving images using linq too?

what about resizing?

what do you think of C# instead of VB?;)

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by Marc at 11/25/2008 7:04 PM
Gravatar
Great stuff. I your site has helped me with some of the finer points of linq several times. Thank you.

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by Nanda at 11/26/2008 5:46 AM
Gravatar
Thanks.
Its working.

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by jcob at 12/4/2008 9:55 PM
Gravatar
thanks

its working....thanks...

can you post on how to displaying the image in an asp image control from a database using linq to sql...

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by IWDC at 4/2/2009 10:14 AM
Gravatar
Hello there...I hope you can help me...I have done this to safe an imagen to my DataBase in SQL2008 with LINQ...

DataClassesDataContext db = new DataClassesDataContext();

PRODUCTO Producto_Grabar = new PRODUCTO
{IMAGEN = FUImagenProducto.FileBytes}

db.PRODUCTOs.InsertOnSubmit(Producto_Grabar);

db.SubmitChanges();

Producto_Grabar -> Is an object of my Table PRODUCTO.

FUImagenProducto -> Is a FileUpload Control.

I have already the bytes of the image in my database but when I try to retrive this image and then show it in a GridView Control in ASP.NET it shows a blank colum.

I have done this to retrieve the image from my database:

DataClassesDataContext db = new DataClassesDataContext();
var Products = from p in db.PRODUCTOs
select new
{
p.IMAGEN,
p.PRICE
}
with this I have the bytes of the image that I want to show in my webpage. Then...

MyGridViewControl.DataSourse = Products;

But this doesnt shows the Image just the PRICE Column...

Please Help...

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by IWDC at 4/2/2009 12:38 PM
Gravatar
Hello there...I hope you can help me...I have done this to safe an imagen to my DataBase in SQL2008 with LINQ...

DataClassesDataContext db = new DataClassesDataContext();

PRODUCTO Producto_Grabar = new PRODUCTO
{IMAGEN = FUImagenProducto.FileBytes}

db.PRODUCTOs.InsertOnSubmit(Producto_Grabar);

db.SubmitChanges();

Producto_Grabar -> Is an object of my Table PRODUCTO.

FUImagenProducto -> Is a FileUpload Control.

I have already the bytes of the image in my database but when I try to retrive this image and then show it in a GridView Control in ASP.NET it shows a blank colum.

I have done this to retrieve the image from my database:

DataClassesDataContext db = new DataClassesDataContext();
var Products = from p in db.PRODUCTOs
select new
{
p.IMAGEN,
p.PRICE
}
with this I have the bytes of the image that I want to show in my webpage. Then...

MyGridViewControl.DataSourse = Products;

But this doesnt shows the Image just the PRICE Column...

Please Help...

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by Web developers at 11/27/2009 9:39 AM
Gravatar
That was an inspiring post,

Keep up the good work,

Anyway, thanks for the post

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by Andrew at 1/8/2010 5:40 PM
Gravatar
FYI, your byte array is one byte too long due to the way VB.NET declares arrays (you specify its upper bound, not its length--as you would do in C#).

Your declaration should be more like:
Dim fileArray(photoFileUpload.PostedFile.ContentLength-1) As Byte

We had a similar problem in our app and now I'm cleaning the data that's been corrupted by this. For those that have been bitten by this as well, assuming your documents (or images or whatever) table stores byte size and binary data in FileSize and FileContent fields, you'd fix by running the following SQL statement:

UPDATE MyDocumentsTable
SET FileContent.Write(NULL, FileSize - 1, NULL), FileSize = FileSize - 1
WHERE FileSize > 0

You could use DataLength to find the end of the binary contents instead if you're not caching size somewhere.

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by Andrew at 1/8/2010 5:45 PM
Gravatar
Oops, and following up, here's a query to run against your documents table to see if you're affected by this bug:

SELECT SUBSTRING(FileContent,DATALENGTH(FileContent),1), COUNT(*)
FROM Documents
WHERE FileSize > 0
GROUP BY SUBSTRING(FileContent,DATALENGTH(FileContent),1)


If you get one result row showing character 0x00, then you've got this issue. Run it in SQL Server Management Studio so you can see the result. Visual Studio (2008 at least) will just show "<Binary data>".

This problem also illustrates another fun indexing fact: SQL Server substring's offset counts from 1 while the .WRITE command counts from zero in its offset.

# re: Uploading an image or file using LINQ TO SQL (System.Linq.Data.Binary)

Left by free term papers at 3/10/2010 1:13 PM
Gravatar
Such a great information, I hope it'll help me to resolve all my problems

Your comment:



 (will not be displayed)


 
 
 
Please add 7 and 4 and type the answer here:
 

Live Comment Preview:

 
«March»
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910