How to save photos in sql server

Hello,
How can I save photos as varbinary(max) in sql server from vb. net.
RIASAsked:
Who is Participating?
 
zephyr_hex (Megan)Connect With a Mentor DeveloperCommented:
You convert the file to a byte array.

Here's a c# version:
var imageBytes = new byte[file.ContentLength];
using (BinaryReader reader = new BinaryReader(file.InputStream))
{
	imageBytes = reader.ReadBytes(file.ContentLength);
}
if (imageBytes.Length > 0)  
{
    //save imageBytes to your db
}

Open in new window


the VB version would be something like:

Dim imageBytes = New Byte(file.ContentLength - 1) {}
Using reader As New BinaryReader(file.InputStream)
	imageBytes = reader.ReadBytes(file.ContentLength)
End Using
If imageBytes.Length > 0 Then
     'save imageBytes to your db
End If

Open in new window

0
 
Pawan KumarConnect With a Mentor Database ExpertCommented:
If you are fine with stored procedure(database) then you can do something like below.

From VB.NET just call a stored procedure and SP will take care of everything.

CREATE TABLE SaveImageInDb
(
      Field1      int
	 ,ImageName   varchar(100)
	 ,Field2      varbinary(max)
)
GO

INSERT INTO SaveImageInDb VALUES 
(1, 'pawan.jpg',NULL)
GO

UPDATE SaveImageInDb
SET    Field2 = (SELECT *
                FROM   OPENROWSET(BULK 'C:\pawan\pawan.jpeg',
                       SINGLE_BLOB) AS x)
WHERE Field1 = 1

select * from SaveImageInDb

Open in new window


OUTPUT

/*------------------------

select * from SaveImageInDb

------------------------*/
Field1      ImageName                                                                                            Field2
----------- ---------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1           pawan.jpg                                                                                            0xFFD8FFE000104A46494600010100000100010000FFE1006245786966000049492A0008000000010069870400010000001A000000000000000100869207002C0000002C000000000000004153434949000000287777772E70686F2E746F292050686F746F456E67696E653A3A436F6C6C6167653A3A310000FFDB0043000302

(1 row(s) affected)

Open in new window

1
 
RIASAuthor Commented:
Thanks Pawan,
Will give a try today and brb.
0
 
Pawan KumarDatabase ExpertCommented:
Incorrect comment selected.
0
 
Pawan KumarDatabase ExpertCommented:
question abandoned.
Provided multiple valid solutions.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.