Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am developing an on line test application. I want to upload image into database but my image is stored in a particular cell of an excel file? Is it possible to save an image into database from excel file? Please help me out.
Posted
Comments
shijuse 18-Oct-11 0:47am    
Hi Qureshali
The better way i think create a seprate image folder in the application and save images in that folder and that image path you have to store in the database
Qureshali 18-Oct-11 0:58am    
but i have an excel file with 1000+ questions and each question has an Image????

 
Share this answer
 
C#
 <asp:gridview id="GridView3" runat="server" autogeneratecolumns="False" datakeynames="IdBanner" xmlns:asp="#unknown">
       EmptyDataText="No Record Found." ShowFooter="True" CellPadding="4" 
                ForeColor="#333333" GridLines="None"  CellSpacing ="2" onrowcommand="GridView3_RowCommand" >
             <rowstyle backcolor="#EFF3FB" />          
            <emptydatarowstyle bordercolor="Red" borderstyle="Double" forecolor="Red">
                HorizontalAlign="Center" />            
            <columns>
            <%--==========================================================================--%>
	             <asp:templatefield headertext="Id" visible="true">
	            <itemtemplate>	            
	            <asp:label id="lblId" runat="server" text="<%#Eval("Id") %>"></asp:label>
	            </itemtemplate>
	            </asp:templatefield>
	            <%-- ===================================================--%>
	             <asp:templatefield headertext="Image" itemstyle-horizontalalign="Left" headerstyle-horizontalalign="Left">                  
                  <edititemtemplate>
                  <asp:fileupload id="FileUploadEdit" runat="server" />
                  </edititemtemplate>
                  <itemtemplate>   
                <asp:image id="ImageIT" runat="server" width="40px" height="40px" imageurl="<%# "../Handler.ashx?IdBanner=" + Eval("IdBanner")%>" />
                  </itemtemplate>  
                   <footertemplate>  
                   <asp:fileupload id="FileUploadN" runat="server" />
                   </footertemplate>  
                   </asp:templatefield> 
             
	            <asp:templatefield headertext="" showheader="False"> 
	            <edititemtemplate> 
  <asp:linkbutton id="LinkButton1" runat="server" causesvalidation="True" commandname="Update" commandargument="<%# Container.DataItemIndex %>" onclientclick="return EditConfirmation();" tooltip="Update Record"></asp:linkbutton> 
  <asp:linkbutton id="LinkButton2" runat="server" causesvalidation="False" commandname="Cancel" commandargument="<%# Container.DataItemIndex %>" tooltip="Cancel Edit"></asp:linkbutton> 
</edititemtemplate>
                 <itemtemplate>
                 <%--OnClick = "Edit"--%>
       <asp:linkbutton id="lnkEdit" runat="server" text="" commandname="Edit" commandargument="<%# Container.DataItemIndex %>"></asp:linkbutton>
   </itemtemplate>
                <footertemplate> 
  <asp:linkbutton id="LinkButton2" runat="server" causesvalidation="False" commandname="AddNew" forecolor="White" tooltip="Add New Record"></asp:linkbutton> 
                </footertemplate> 
                
                </asp:templatefield> 
                <asp:templatefield headertext="" showheader="False"> 
                <itemtemplate> 
  <asp:linkbutton id="LinkButton4" runat="server" causesvalidation="False" commandname="Delete" commandargument="<%# Container.DataItemIndex %>" tooltip="Eliminar Record">
 </asp:linkbutton> 
                </itemtemplate>
                </asp:templatefield> 
</columns> 
            <footerstyle backcolor="#1A4D8A" font-bold="True" forecolor="White" />
            <pagerstyle backcolor="#2461BF" forecolor="White" horizontalalign="center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333"  />
            <HeaderStyle BackColor="#1A4D8A" Font-Bold="True" ForeColor="White"   />          
            <editrowstyle horizontalalign="Center" verticalalign="Middle" backcolor="#2461BF" />
            <alternatingrowstyle backcolor="White" />
        </emptydatarowstyle></asp:gridview>



Above is the Gridview Code in which i use Image control .For display image in this image control i use a Handler.below is the Handler.
handler.ashx

C#
<![CDATA[<%@ WebHandler Language="C#" Class="Handler" %>]]>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Net;

public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context)
    {
        
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["conm"].ConnectionString;
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "select Image from Banners where IdBanner=@IdBanner";
            //cmd.CommandText = "Select ImageName,Image from Images where ID =@ID";
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Connection = con;

            SqlParameter ImageID = new SqlParameter("@IdBanner", System.Data.SqlDbType.Int);
            ImageID.Value = context.Request.QueryString["IdBanner"];
            cmd.Parameters.Add(ImageID);
            con.Open();
            SqlDataReader dReader = cmd.ExecuteReader();

           
        if (dReader.Read())
            {
                string impath = System.Web.HttpContext.Current.Server.MapPath("~/Images/no-image.gif"); 
            //    Server.MapPath("~/XMLSupplier/");
            //string impath=server   
           // string impath="~/Images/no-image.gif";
               if (string.IsNullOrEmpty(Convert.ToString(dReader["Image"])))
               {
                   context.Response.ContentType = "image/jpg";
                   context.Response.BinaryWrite((byte[])ConvertImageFiletoBytes(impath));
               }
               else
               {
                   context.Response.ContentType = "image/jpg";
            context.Response.BinaryWrite((byte[])dReader["Image"]);
               }//context.Response.BinaryWrite((byte[])Convert.ToByte(no-image.gif));
            }
            dReader.Close();
            con.Close();
        
        
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    public byte[] ConvertImageFiletoBytes(string ImageFilePath)
    {
        byte[] _tempByte = null;
        if (string.IsNullOrEmpty(ImageFilePath) == true)
        {
            //throw new ArgumentNullException("Image File Name Cannot be Null or Empty", "ImageFilePath");
            throw new ArgumentNullException("Image File Name Cannot be Null or Empty", "ImageFilePath");
            return null;

        }
        try
        {
            System.IO.FileInfo _fileInfo = new System.IO.FileInfo(ImageFilePath);
            long _NumBytes = _fileInfo.Length;
            System.IO.FileStream _FStream = new System.IO.FileStream(ImageFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FStream);
            _tempByte = _BinaryReader.ReadBytes(Convert.ToInt32(_NumBytes));
            _fileInfo = null;
            _NumBytes = 0;
            _FStream.Close();
            _FStream.Dispose();
            _BinaryReader.Close();
            return _tempByte;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

}

Now you can write code for save image in database in bytes format on Gridview Row Command Event. Below is the Example.

C#
 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
 if (e.CommandName == "AddNew")
        {
            FileUpload FileUploadN = (FileUpload)GridView3.FooterRow.FindControl("FileUploadN");
            TextBox txtNEWLink = (TextBox)GridView3.FooterRow.FindControl("txtNEWLink");
           

            BannerBean F = new BannerBean();
            Int32 imglen = 0;
            FileUpload imgK = (FileUpload)FileUploadN;

            Byte[] imgByte = null;
            if (imgK.HasFile && imgK.PostedFile != null)
            {
                //To create a PostedFile
                HttpPostedFile File = FileUploadN.PostedFile;
                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            F.ImgSize = imglen;
            F.Image = imgByte;
            F.Link = txtNEWLink.Text;           
            BannerDBManager dm = new BannerDBManager();
            dm.AddBanner(F);
           
        }
}

These values will pass to Business Object Class.
I m writting code for this class as example.

C#
public void AddBanner(BannerBean F)
   {
       String cs = WebConfigurationManager.ConnectionStrings["conm"].ConnectionString;
       SqlConnection conn = new SqlConnection(cs);
       conn.Open();
       SqlCommand cmd = new SqlCommand();
       cmd.Connection = conn;
       cmd.Parameters.Clear();
       cmd.CommandType = CommandType.Text;
       cmd.CommandText = " insert into Banner (Image,Link) values (@Image,@Link)";

       if (string.IsNullOrEmpty(Convert .ToString (F.Image)))
       { cmd.Parameters.Add("@Image", SqlDbType.Image).Value = DBNull.Value; }
       else
       { cmd.Parameters.Add("@Image", SqlDbType.Image).Value = F.Image; }

       if (string.IsNullOrEmpty(F.Link))
       {
           cmd.Parameters.Add("@Link", SqlDbType.NVarChar).Value = DBNull.Value;   }
       else
       { cmd.Parameters.Add("@Link", SqlDbType.NVarChar).Value = F.Link; }
       cmd.ExecuteNonQuery();
       conn.Close();
   }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900