Objective
In this article, I am going to show you How to insert an image from ASP.Net
application to SQL Server using LINQ to SQL and how to retrieve image from SQL
Server data base using LINQ to SQL and display to an Image control.
Block Diagram of solution
Description of table
For my purpose, I have created a table called ImageTable.
- Id is primary key.
- Name column will contain name of the image file.
- FileSource column will contain binary of image. Type of this column is image.
Create ASP.Net Web Application
Open visual studio and from File menu select New Project and then from Web tab
select new web application. Give meaningful name to your web application.
Create DBML file using LINQ to SQL class.
For detail description on how to use LINQ to SQL class read
HERE
- Right click on the project and select add new item.
- From DATA tab select LINQ to SQL Class.
- On design surface select server explorer.
- In server explorer and add new connection.
- Give database server name and select database.
- Dragged the table on the design surface.
Once all the steps done, you will have a dbml file created.
Design the page
- I have dragged one FileUpload control and a button for upload purpose.
- One text box. In this text box user will enter Id of the image to be fetched.
- One button to fetch the image from database.
- One Image control to display image from database.
Default.aspx
Saving image in table
On click event of Button 1 Image upload will be done.
In this code- First checking whether FileUplad control contains file or not.
- Saving the file name in a string variable.
- Reading file content in Byte array.
- Then converting Byte array in Binary Object.
- Creating instance of data context class.
- Creating instance of ImageTable class using object initializer. Passing Id as
hard coded value. Name as file name and FileSource as binary object.
Retrieving Image from table
On click event of button2 Image will be fetched of a particular Id. Image Id
will be given by user in text box.
In above code, I am calling a generic HTTP handler. As query string value from
textbox1 is appended to the URL of HTTP handler. To add HTTP handler, right
click on project and add new item. Then select generic handler from web tab.
In above code,
- Reading query string in a variable.
- Calling a function returning ShowEmpImage returning Stream.
- In ShowEmpImage , creating object DataContext class .
- Using LINQ fetching a particular raw from table of a particular ID.
- Converting image column in memory stream. In this case FileSource column is
containing image.
- Converting stream into byte array.
- Reading byte array in series of integer.
- Using Output stream writing the integer sequence.
Running application
For your reference Source code is given as below
Default.aspx.cs
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Data.Linq;
using System.IO;
namespaceuploadingImageusingLInqtoSQl
{
publicpartialclass_Default
: System.Web.UI.Page
{
protectedvoidPage_Load(object
sender, EventArgs e)
{
}
protectedvoid Button1_Click(object
sender, EventArgs e)
{
if (FileUpload1.HasFile &&
FileUpload1.PostedFile.ContentLength > 0)
{
stringfileName =
FileUpload1.FileName;
byte[] fileByte = FileUpload1.FileBytes;
BinarybinaryObj =
newBinary(fileByte);
DataClasses1DataContext context =
newDataClasses1DataContext();
context.ImageTables.InsertOnSubmit(
newImageTable
{ Id = "xyz",
Name = fileName,
FileSource = binaryObj });
context.SubmitChanges();
}
}
protectedvoid Button2_Click(object
sender, EventArgs e)
{
Image1.ImageUrl = "~/MyPhoto.ashx?Id="+TextBox1.Text;
}
}
}
MyPhto.ashx.cs
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
using System.IO;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
namespaceuploadingImageusingLInqtoSQl
{
///<summary>
/// Summary description for MyPhoto
///</summary>
publicclassMyPhoto
: IHttpHandler
{
publicvoidProcessRequest(HttpContext
context)
{
string id = context.Request.QueryString["Id"];
context.Response.ContentType = "image/jpeg";
Streamstrm = ShowEmpImage(id);
byte[] buffer =
newbyte[4096];
intbyteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq> 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
}
publicStreamShowEmpImage(string
id)
{
DataClasses1DataContext context1 =
newDataClasses1DataContext();
var r = (from a
in context1.ImageTables
wherea.Id == id select a).First();
returnnewMemoryStream(r.FileSource.ToArray());
}
publicboolIsReusable
{
get
{
returnfalse;
}
}
}
}
I hope this post is useful. Thanks for reading. Happy Coding.