Tuesday, October 19, 2010

Store Image and Video in Database using ASP.Net and C#

Introduction:
It is a common case to store image and video in database. But store image/video in database takes huge amount of space. So after some time in Google I learn a technique to store image/video in database easily. In my case I store only the name of the image/video in a varchar field in database and the actual file uploaded in the server. Let see the simple but very useful technique to store image/video.
Step1: First we create a simple ASP.Net project named StoreImage. An asp page and a folder to load the image/video. The solution explorer looks like

Step2: In aspx page I use only a file up loader control of asp and a two button one for upload and another for save. The aspx page code as follows,

<form id="uploadForm" runat="server">

<table>

<tr>

<td>

Uploaded Image:

td>

<td>

<asp:Image ID="imageFile" runat="server" />

td>

tr>

<tr>

<td>

<asp:FileUpload ID="fileUploadImage" runat="server" />

td>

<td>

<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click"/>

td>

tr>

<tr>

<td colspan="2">

<asp:Label ID="lblError" runat="server" ForeColor="Red">asp:Label>

td>

tr>

<tr>

<td colspan="2">

<asp:Button ID="btnSave" runat="server" Text="Save Image"

onclick="btnSave_Click" />

td>

tr>

table>

form>



Step3: In the code behind use the following code to upload the image in server’s particular folder in our case the folder is ‘Uploaded Image’

protected void btnUpload_Click(object sender, EventArgs e)

{

if (fileUploadImage.PostedFile != null && fileUploadImage.PostedFile.ContentLength > 0)

{

//Get the file extension and check if it is jpg,png or wmv.

fileExtension = Path.GetExtension(fileUploadImage.PostedFile.FileName);

//If file type jpg/png/wmv then enter the block

if (fileExtension.ToLower().Equals(".jpg") || fileExtension.ToLower().Equals(".png") || fileExtension.ToLower().Equals(".wmv"))

{

//get file size

fileSize = fileUploadImage.PostedFile.ContentLength;

//if file size more than 4MB then show error message

if (fileSize / 1024 > 4096)

{

lblError.Text = "File size can not be more than 4MB";

return;

}

else

{

//get the uploaded file name

fileName = Path.GetFileName(fileUploadImage.PostedFile.FileName);

//save the file in location of server

fileUploadImage.PostedFile.SaveAs(HttpContext.Current.Server.MapPath("~/Uploaded Image/" + Path.GetFileName(fileUploadImage.PostedFile.FileName)));

//get the server URI

ServerUri = System.Configuration.ConfigurationManager.AppSettings["ServerUrl"].ToString();

//Create the image URI

imageUri = ServerUri + "/Uploaded Image/" + fileName;

//Show the uploaded iamge in imagefile

imageFile.ImageUrl = ServerUri + "/Uploaded Image/" + fileName;

}

}

else

{

lblError.Text = "Unsupported file format. Please select jpg, pig or wmv file";

return;

}

}

else

{

lblError.Text = "No file selected";

return;

}

}

We assume that we just upload jpg png or wmv file.

To get the server URL we add an extra line in web.config file. The line is

<appSettings>

<add key ="ServerUrl" value="http://localhost:4122" />

appSettings>

For your case it may be different. After show the location of file and click the Upload button my page looks like


Step4: Now we want to save the image name in database. To do so first we read the file name from server then we save it to database. Suppose our database hold a table named image which has two field OID and ImageName. So to save it in database we need the following code in the Save button’s event handler.

bool SaveImage()

{

bool result = false ;

if (imageUri != null)

{

string[] imageName = imageUri.Split('/');

//check the file extension if the extension jpg/png then content type IMG

if (imageName[imageName.Length - 1].Contains("jpg") || imageName[imageName.Length - 1].Contains("png"))

{

SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);

string query = "";

query += " insert into t_ image (OID, ImageName) ";

query += " values (@OID, @ ImageName) ";

try

{

SqlCommand command = new SqlCommand();

command.Connection = conn;

command.CommandType = System.Data.CommandType.Text;

command.CommandText = query;

command.Parameters.AddWithValue("OID", "1");

command.Parameters.AddWithValue("ImageName ", imageName[imageName.Length - 1]);

conn.Open();

if (command.ExecuteNonQuery() == 1)

{

result = true;

}

}

catch (Exception ex)

{

result = false;

}

finally

{

conn.Close();

conn.Dispose();

}

}

}

return result;

}


protected void btnSave_Click(object sender, EventArgs e)

{

if (SaveImage())

{

lblError.Text = "Image Save Successfully";

}

}

Here imageUri is a static global field which hold the image url when upload the image to the server.

Hope it will help you little bit. Thank you very much. For any query please don’t be hesitate to write me.

Shimul Mahmud

azkhairuzzaman@gmail.com



1 comment:

  1. Admin plz upload the code of how to store pdf in mssql server2005 database and retrieve PDF in gridview and when I click the PDF value in grid view then the PDF open in another page having I frame control...... I store the PDF in database but cannot retrieve........ plz admin if u do it then do .
    ..my project hanging bcz of this......I also use ur above code..... amit saini

    ReplyDelete