How to save photos in sql server

RIAS
RIAS used Ask the Experts™
on
Hello,
How can I save photos as varbinary(max) in sql server from vb. net.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2010
Commented:
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

Pawan KumarDatabase Expert
Awarded 2016
Top Expert 2016
Commented:
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

Author

Commented:
Thanks Pawan,
Will give a try today and brb.
Pawan KumarDatabase Expert
Awarded 2016
Top Expert 2016

Commented:
Incorrect comment selected.
Pawan KumarDatabase Expert
Awarded 2016
Top Expert 2016

Commented:
question abandoned.
Provided multiple valid solutions.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial